package com.pro.ydl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.achartengine.GraphicalView;
import org.achartengine.model.SeriesSelection;
import org.xml.sax.Parser;

import ydl.wheel.widget.ArrayWheelAdapter;
import ydl.wheel.widget.NumericWheelAdapter;
import ydl.wheel.widget.OnWheelChangedListener;
import ydl.wheel.widget.WheelView;

import com.pro.ydl.CommonFunction.YDLButtonSound;
import com.pro.ydl.service.MainService;

import YDLControl.Control;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.app.TabActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Color;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TabWidget;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;

enum EM_TABLE_ARRANGETIME_TYPE {
	DAY, WEEK, MON, YEAR
};

enum EM_TABLE_SHOW_TYPE {
	TIME, DISTANCE, CALORIE, SPEED
};

/* TAB1 FRAME STATUS */
enum EM_USERINFO_TAB_FRAME_STS {
	LOGOUTTABLE, LOGINTABLE
};

/* TAB2 FRAME STATUS */
enum EM_MORETABLE_TAB_FRAME_STS {
	TIMESELECT, TABLETIME, TABLEDISTANCE, TABLECALORIE, TABLESPEED
};

/* TAB3 FRAME STATUS */
enum EM_RUNNINGIINFO_TAB_FRAME_STS {
	TIME, DEFAULT_LISTVIEW, TABLE, SEARCH_LISTVIEW
};

/* CURRENT TAB NO */
enum EM_CURRENT_TAB_NO {
	USERINFO, MORMTABLE, RUNNINGINFO, SETTING
};

public class MainHomeActivity extends TabActivity implements
		OnTabChangeListener, OnTouchListener, OnCheckedChangeListener,
		OnItemClickListener, OnPageChangeListener {
	private final Handler handle = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			switch (msg.what) {
			case MESSAGE_SETTING_GET_USE_INFO: {
				if (progdialogSettingGetUserInfo.isShowing()) {
					progdialogSettingGetUserInfo.dismiss();
				}
				if (0 == msg.arg1) {
					ShowToast(MainHomeActivity.this, "获取用户信息失败");
				} else {
					SettingTabFrameShow();
					bSettingReqUserInfoFlag = true;
				}
			}
				break;
			case MESSAGE_SETTING_SUBMIT_USER_INFO: {
				if (progdialogSettingSubmitUserInfo.isShowing()) {
					progdialogSettingSubmitUserInfo.dismiss();
				}
				if (0 == msg.arg1) {
					ShowToast(MainHomeActivity.this, "提交用户信息失败");
				} else {
					ShowToast(MainHomeActivity.this, "修改用户信息成功");
				}
			}
				break;
			case MESSAGE_MAIN_DOWNLOAD_DATA_TO_BD: {
				if (progdialogMainDownLoadToBD.isShowing()) {
					progdialogMainDownLoadToBD.dismiss();
				}
				if (-1 == msg.arg1) {
					ShowToast(MainHomeActivity.this, "没有数据更新");
				} else if (0 == msg.arg1) {
					ShowToast(MainHomeActivity.this, "更新数据失败");
				} else {
					ShowToast(MainHomeActivity.this, "更新数据成功");
				}
			}
				break;
			case MESSAGE_TAB2_SEARCH_RESULT: {
				if (progdialogTab2Search.isShowing()) {
					progdialogTab2Search.dismiss();
				}
				if (0 == msg.arg1) {
					if(strDownLoadErrorMessage.contains("您查询的数据不存在"))
					{
						ShowToast(getApplicationContext(), "您查询的数据不存在，请赶紧运动吧");
					}
					else
					{
						ShowToast(getApplicationContext(), "您的网络不给力，待会再试试吧");
					}
				} else {
					// 画面跳转查询
					if (EM_TABLE_SHOW_TYPE.TIME == emCurrentTableShowType) {
						emMoreTableTabFrameSts = EM_MORETABLE_TAB_FRAME_STS.TABLETIME;
					} else if (EM_TABLE_SHOW_TYPE.DISTANCE == emCurrentTableShowType) {
						emMoreTableTabFrameSts = EM_MORETABLE_TAB_FRAME_STS.TABLEDISTANCE;
					} else if (EM_TABLE_SHOW_TYPE.CALORIE == emCurrentTableShowType) {
						emMoreTableTabFrameSts = EM_MORETABLE_TAB_FRAME_STS.TABLECALORIE;
					} else {
						emMoreTableTabFrameSts = EM_MORETABLE_TAB_FRAME_STS.TABLESPEED;
					}
					MoreTableTabFrameInit();
					Tab2MoreTableFrameTitleinital();
				}
			}
				break;
			case MESSAGE_TAB3_DEFAULTLISTSEARCH_RESULT: {
				if (progdialogTab3Search.isShowing()) {
					progdialogTab3Search.dismiss();
				}
				Tab3RunningInfoFrameTitleinital();
				RunningInfoTabFrameInit();
			}
				break;
			case MESSAGE_TAB3_USERLISTSEARCH_RESULT: {
				if (progdialogTab3Search.isShowing()) {
					progdialogTab3Search.dismiss();
				}
				Tab3RunningInfoFrameTitleinital();
				RunningInfoTabFrameInit();
				// 默认list都去请求
			}
				break;
			case MESSAGE_TAB3_TABLESEARCH_RESULT: {
				if (progdialogTab3Search.isShowing()) {
					progdialogTab3Search.dismiss();
				}
				Tab3RunningInfoFrameTitleinital();
				RunningInfoTabFrameInit();
				// 默认list都去请求
			}
				break;
			}
		}
	};
	private ProgressDialog progdialogSettingGetUserInfo = null;
	private ProgressDialog progdialogSettingSubmitUserInfo = null;
	private ProgressDialog progdialogMainDownLoadToBD = null;
	private ProgressDialog progdialogTab2Search = null;
	private ProgressDialog progdialogTab3Search = null;
	TabHost mTabHost;
	TabWidget mTabWidget;
	private static final String Tag = "TabActivity";
	private static final int MESSAGE_SETTING_GET_USE_INFO = 1;
	private static final int MESSAGE_SETTING_SUBMIT_USER_INFO = 2;
	private static final int MESSAGE_MAIN_DOWNLOAD_DATA_TO_BD = 3;
	private static final int MESSAGE_TAB2_SEARCH_RESULT = 4;
	private static final int MESSAGE_TAB3_DEFAULTLISTSEARCH_RESULT = 5;
	private static final int MESSAGE_TAB3_TABLESEARCH_RESULT = 6;
	private static final int MESSAGE_TAB3_USERLISTSEARCH_RESULT = 7;
	TextView titlename;
	ImageButton userinfotabtitleleftbutton;
	ImageButton userinfotabtitlerightbutton;
	LinearLayout runninginfotabdatepicker;

	ListView tab3listview;
	TextView runninginfotabtimedurringtextview;
	TextView runninginfotabtotolesumtextview;
	// table data start time and end time
	String sTableDurringTime;
	String sRunningID;
	LinearLayout moretabletabdatepicker;
	RadioGroup moretabletabdateradiogroup, moretabletabshowtyperadiogroup;
	TextView moretableselectarragetextview, moretableselecttypetextview;
	ImageButton moretabletabfavoratebutton;
	TextView moretabletabtimedurringtextview;
	TextView moretabletabtotolesumtextview;

	ImageButton imagebuttonUserInfoDeleteTable;
	TextView textviewUserInfoTimeDurring;
	TextView textviewUserInfoTotleSum;

	int iYearUserSelect, iMonthsUserSelect, iDayUserSelect;
	int iYearRunTableUserSelect, iMonthsRunTableUserSelect,
			iDayRunTableUserSelect;

	int iRunningInfoYear, iRunningInfoMonths, iRunningInfoDay;

	EM_TABLE_ARRANGETIME_TYPE emCurrentTableArrangeTimeType;
	EM_TABLE_SHOW_TYPE emCurrentTableShowType;

	String sCurrentTableTimedurring;
	String sStartTime, sStopTime;
	String sSessionID;
	double[] dCurrentTableXDataArray;
	double[] dCurrentTableYDataArray;
	ArrayList arrRunningID=new ArrayList();
	EM_RUNNINGIINFO_TAB_FRAME_STS emRunningInfoTabFrameSts;
	EM_MORETABLE_TAB_FRAME_STS emMoreTableTabFrameSts;
	EM_USERINFO_TAB_FRAME_STS emUserInfoTabFrameSts;
	EM_CURRENT_TAB_NO emCurrentTabNo;
	boolean bCurrentRegisterSts;
	String sUserID, sSession;

	SharedPreferences sharedPreferences;
	Editor editor;

	int iPreTabNo;

	ViewPager userinfoviewpager;
	View moretablenouseview;
	View runninginfonouseview;
	ImageButton runninginfofavoritebutton;
	ImageButton tab3tablefavorate;
	GraphicalView moretabletableview;
	GraphicalView runninginfotableview;

	RelativeLayout tab3relativelayout;
	RelativeLayout tab3tablerelativelayout;
	LinearLayout layoutTab2MoreReportText;
	LinearLayout layoutTab2TimeView;
	LinearLayout layoutTab2UserTypeSelect;
	RelativeLayout layoutTab2Table;

	ArrayList<Hashtable<String, Object>> arraylistSimulateData;

	MyPagerAdapter mPagerAdapter;

	int iViewPagerCurrentPage;

	ArrayList<GraphicalView> tableviews;

	Control database;

	int i20TablesRunningId[];
	int i20TablesRunningIdIndex;

	boolean bRunningInfoTableFromDefaultListview;
	boolean bDestoryApp = false;
	boolean IsQuit = false;
	EditText ETSettingEmail, ETSettingOldPasswd,ETSettingNewPasswd,ETSettingNewPasswdConfirm, ETSettingHeight,
			ETSettingWeight;
	RadioGroup RGSettingSex;
	ImageButton IBSettingSubmit;
	ImageButton IBSettingLogout;
	// user info
	String strSex = "";
	String strUserHeight = "";
	String strUserWeight = "";
	String strUserbirthday = "";
	String strUserYear = "";
	String strUserMonth = "";
	String strUserDay = "";
	String strDownLoadErrorMessage = "";
	Date dataStartTime, dataEndTime;
	// set the birthday adapter
	private static final String[] month = { "1月", "2月", "3月", "4月", "5月", "6月",
			"7月", "8月", "9月", "10月", "11月", "12月" };
	private static String[] days = new String[] { "1日", "2日", "3日", "4日", "5日",
			"6日", "7日", "8日", "9日", "10日", "11日", "12日", "13日", "14日", "15日",
			"16日", "17日", "18日", "19日", "20日", "21日", "22日", "23日", "24日",
			"25日", "26日", "27日", "28日", "29日", "30日", "31日" };
	private static Calendar cal = Calendar.getInstance();
	private static int intCurrentYear = cal.get(Calendar.YEAR);
	private static int intYearLength = intCurrentYear - 1900 + 1;
	private static String[] year = new String[intYearLength];
	private ArrayAdapter<String> adpBirthdayYear;
	private ArrayAdapter<String> adpBirthdayMonth;
	private ArrayAdapter<String> adpBirthdayDay;
	private Spinner spinnerYear;
	private Spinner spinnerMonth;
	private Spinner spinnerDay;
	private boolean bLeapYear = false;

	int[] iStoreTableIdArray = null;
	boolean bQuitDialog = false;
	boolean bUnregTabChange = false;
	ContentValues getUserInfo;
	boolean bSettingReqUserInfoFlag = false;
	boolean bFirstAppRunn = true;
	boolean bFirstShowTab3 = true;
	//tab1 start frame view paper
	ViewPager mStartFrameViewPager = null;
	ArrayList<View> lvStartFrameViews=null; 
	String sMoreTableSummary;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// copyDatabaseFile(this,true);
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main_home_activity_layout);
		/******************************* control information tab initial ****************************/
		YDLApplication YDLApplication = (YDLApplication) getApplication();
		YDLApplication.setAddNum();
		// data save management initial
		MainHomeActivityPreferenceinit();
		// title initial
		MainHomeActivityTitleControlInitial();
		// user info initial
		UserInfoTabControlinit();
		// more table initial
		MoreTableControlinit();
		// running info initial
		RunningInfoTabControlinit();
		// setting tab initial
		SettingTabcontrolinit();
		// quit tab initial
		QuitTabControlinit();
		// resume all initial data from XML file
		GetFrameDataInitial();
		// database initial
		MainHomeActivityDataBaseInitial();
		// TabHost object initial
		mTabHost = getTabHost();
		mTabWidget = mTabHost.getTabWidget();
		mTabWidget.setBackgroundColor(Color.rgb(23, 23, 23));
		mTabHost.addTab(mTabHost
				.newTabSpec("UserInfo")
				.setContent(R.id.tab1)
				.setIndicator("我的报表",
						getResources().getDrawable(R.drawable.social_person)));
		mTabHost.addTab(mTabHost
				.newTabSpec("MoreTable")
				.setContent(R.id.tab2)
				.setIndicator("更多报表",
						getResources().getDrawable(R.drawable.action_search)));
		mTabHost.addTab(mTabHost
				.newTabSpec("RunInfo")
				.setContent(R.id.tab3)
				.setIndicator(
						"跑步信息",
						getResources().getDrawable(
								R.drawable.collections_view_as_list)));
		mTabHost.addTab(mTabHost
				.newTabSpec("Setting")
				.setContent(R.id.tab4)
				.setIndicator("设置",
						getResources().getDrawable(R.drawable.action_settings)));
		mTabHost.addTab(mTabHost
				.newTabSpec("Quit")
				.setContent(R.id.tab5)
				.setIndicator(
						"退出",
						getResources().getDrawable(
								R.drawable.av_pause_over_video)));
		settabstyle();
		// set current tab
		SetCurrentTab();
		// tab change listener
		mTabHost.setOnTabChangedListener(this);

		/******************************* frame tabs initial ****************************/
		// title initial
		MainActivityTitleFrameInitial();
		// user info tab initial
		UserInfoTabFrameInit();
		// more table tab initial
		MoreTableTabFrameInit();
		// running info
		// RunningInfoTabFrameInit();
		tab3SearchThreadHandle();
		// setting tab initial
		SettingTabFrameInit();
		// quit tab initial
		MainActivityEndService();
	    MainActivityStartService();

		// MainActivityDownDataFormWeb();

		// set the event for tab click
		mTabWidget.getChildAt(1).setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == MotionEvent.ACTION_UP) {
					int tabId = mTabHost.getCurrentTab();
					if (false == bCurrentRegisterSts) {
						return false;
					} else {
						if (tabId != 1) {
							return false;
						}
						iPreTabNo = emCurrentTabNo.ordinal();
						emMoreTableTabFrameSts = EM_MORETABLE_TAB_FRAME_STS.TIMESELECT;
						// title frame change
						MainActivityTitleFrameInitial();

						if (true == bFirstAppRunn) {
							bFirstAppRunn = false;
							UserInfoTabFrameInit();
						}
						MoreTableTabFrameInit();
						RunningInfoTabFrameInit();
						//tab3SearchThreadHandle();
						SettingTabFrameInit();
						// save the frame state
						MainActivitySaveFrameStsToLocal();
					}
				}
				return false;
			}
		});
		mTabWidget.getChildAt(2).setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == MotionEvent.ACTION_UP) {
					int tabId = mTabHost.getCurrentTab();
					if (false == bCurrentRegisterSts) {
						return false;
					} else {
						if (tabId != 2) {
							return false;
						}
						iPreTabNo = emCurrentTabNo.ordinal();
						emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.DEFAULT_LISTVIEW;
						// title frame change
						MainActivityTitleFrameInitial();

						if (true == bFirstAppRunn) {
							bFirstAppRunn = false;
							UserInfoTabFrameInit();
						}
						MoreTableTabFrameInit();
						RunningInfoTabFrameInit();
						tab3SearchThreadHandle();
						SettingTabFrameInit();
						// save the frame state
						MainActivitySaveFrameStsToLocal();
					}
				}
				return false;
			}
		});
	}

	/* from stop to start activity frame status flush */

	@Override
	protected void onStart() {
		super.onStart();
		// MainActivityStartService();
	}

	/* from pause to resume activity frame status flush */
	@Override
	protected void onResume() {
		super.onResume();
	}

	/* database initial */
	public void MainHomeActivityDataBaseInitial() {

		database = new Control();
		// database.testDaySumData(this);
		// database.testSpeedData(this);
		// database.testTrackingData(this);
		// if(0 == database.whetherDBNull(this))
		{
			try {
				// database.downloadDataToDB(sSession, new Date(112,7,4), new
				// Date(112,7,5), "1", 0, this);
				// database.downloadDataToDB(sSession, new Date(112,4,5), new
				// Date(112,4,6), "1", 2, this);
				// database.downloadDataToDB(sSession, new Date(112,7,4), new
				// Date(112,4,7), "1", 3, this);
				// Log.i("","");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	/* Preference control initial */
	public void MainHomeActivityPreferenceinit() {
		sharedPreferences = this.getSharedPreferences("YDL",
				Context.MODE_PRIVATE);
		editor = sharedPreferences.edit();
	}

	/* title of APP control initial ,get every object pointer */
	public void MainHomeActivityTitleControlInitial() {
		userinfotabtitleleftbutton = (ImageButton) findViewById(R.id.TitleLeftButton);
		userinfotabtitlerightbutton = (ImageButton) findViewById(R.id.TitleRightButton);
		titlename = (TextView) findViewById(R.id.TitleName);
		// listener
		userinfotabtitleleftbutton.setOnTouchListener(this);
		userinfotabtitlerightbutton.setOnTouchListener(this);

	}

	/* tab1 frame control initial,get every object pointer */
	public void UserInfoTabControlinit() {

		userinfoviewpager = (ViewPager) findViewById(R.id.tab1tableviewpager);
		imagebuttonUserInfoDeleteTable = (ImageButton) findViewById(R.id.tab1IBdeletetable);
		textviewUserInfoTimeDurring = (TextView) findViewById(R.id.tab1TVtimedurring);
		textviewUserInfoTotleSum = (TextView) findViewById(R.id.tab1TVtotle);

		// listener
		imagebuttonUserInfoDeleteTable.setOnTouchListener(this);
		userinfoviewpager.setOnPageChangeListener(this);

		tableviews = new ArrayList<GraphicalView>();
		mPagerAdapter = new MyPagerAdapter();
		userinfoviewpager.setAdapter(mPagerAdapter);
		
		//add by JT
		mStartFrameViewPager = new ViewPager(this);
		LayoutParams tableparam = new LayoutParams(
				LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT
		);
		mStartFrameViewPager.setLayoutParams(tableparam);
	}

	public GraphicalView MainActivityCreateTable(EM_CHART_TYPE emChartType,
			double dXCoordinate[], double dYCoordinate[], String sTableTitle,
			String sXAxisName, String sYAxisName, String sPromptMessage) {
		YDLChartFactory ChartFactory = null;
		if ((null == dXCoordinate) || (null == dYCoordinate)) {
			return null;
		}
		if (dXCoordinate.length != dYCoordinate.length) {
			return null;
		}
		try {
			if (sPromptMessage == "跑步信息") {
				sXAxisName = "跑步时间";
			} else if (dYCoordinate.length == 7) {
				sXAxisName = "周";
			} else if (dYCoordinate.length <= 31 && dYCoordinate.length > 12) {
				sXAxisName = "月";
			} else if (dYCoordinate.length == 12) {
				sXAxisName = "年";
			} else {
				sXAxisName = "日";
			}
			if (EM_CHART_TYPE.EM_CHART_TYPE_LINE == emChartType) {
				ChartFactory = new YDLChartFactory(
						EM_CHART_TYPE.EM_CHART_TYPE_LINE, sPromptMessage);
				ChartFactory.setYDLLineChartCoordinate(dXCoordinate,
						dYCoordinate);
				ChartFactory.setYDLLineChartSettings(sTableTitle, sXAxisName,
						sYAxisName);
				return ChartFactory.getGVview(this);
			} else {
				ChartFactory = new YDLChartFactory(
						EM_CHART_TYPE.EM_CHART_TYPE_BAR, sPromptMessage);
				ChartFactory.setYDLBarChartCoordinate(dXCoordinate,
						dYCoordinate);
				ChartFactory.setYDLBarChartSettings(sTableTitle, sXAxisName,
						sYAxisName);
				return ChartFactory.getGVview(this);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/* tab2 frame control initial,get every object pointer */
	public void MoreTableControlinit() {
		// select frame initial
		moretabletabdatepicker = (LinearLayout) findViewById(R.id.moretabledatePicker);
		moretabletabdateradiogroup = (RadioGroup) findViewById(R.id.radiogroupdate);
		moretabletabshowtyperadiogroup = (RadioGroup) findViewById(R.id.radiogroupshowtype);
		moretableselectarragetextview = (TextView) findViewById(R.id.selectarrageview);
		moretableselecttypetextview = (TextView) findViewById(R.id.selecttypeview);
		moretabletabdateradiogroup.setOnCheckedChangeListener(this);
		moretabletabshowtyperadiogroup.setOnCheckedChangeListener(this);
		// table initial
		moretablenouseview = (View) findViewById(R.id.tab2tableview);
		moretabletabfavoratebutton = (ImageButton) findViewById(R.id.IBfavorite);
		moretabletabfavoratebutton.setOnTouchListener(this);
		moretabletabtimedurringtextview = (TextView) findViewById(R.id.TVtimedurring);
		moretabletabtotolesumtextview = (TextView) findViewById(R.id.TVtab2totlesum);

		// layout initial
		layoutTab2MoreReportText = (LinearLayout) findViewById(R.id.moreReportText);
		layoutTab2TimeView = (LinearLayout) findViewById(R.id.moretabledatePicker);
		layoutTab2UserTypeSelect = (LinearLayout) findViewById(R.id.layoutUserSelect);
		layoutTab2Table = (RelativeLayout) findViewById(R.id.layoutTab2Table);
		MoreTableWheelTimeInit();
	}

	/* tab3 frame control initial,get every object pointer */
	public void RunningInfoTabControlinit() {

		runninginfotabdatepicker = (LinearLayout) findViewById(R.id.runninginfodatePicker);

		tab3listview = (ListView) findViewById(R.id.tab3listview);

		runninginfotabtimedurringtextview = (TextView) findViewById(R.id.tab3TVtimedurring);
		runninginfotabtotolesumtextview = (TextView) findViewById(R.id.tab3TVtotlesum);
		runninginfonouseview = (View) findViewById(R.id.tab3tableview);
		runninginfofavoritebutton = (ImageButton) findViewById(R.id.tab3IBfavorite);
		tab3relativelayout = (RelativeLayout) findViewById(R.id.tab3);
		tab3tablerelativelayout = (RelativeLayout) findViewById(R.id.tab3layouttable);
		tab3tablefavorate = (ImageButton) findViewById(R.id.tab3IBfavorite);
		tab3tablefavorate.setOnTouchListener(this);
		RunningInfoWheelTimeInit();
	}

	/* tab4 frame control initial,get every object pointer */
	public void SettingTabcontrolinit() {
		ETSettingEmail = (EditText) findViewById(R.id.configEmail);
		ETSettingOldPasswd = (EditText) findViewById(R.id.configOldPassword);
		ETSettingNewPasswd =  (EditText) findViewById(R.id.configNewPassword);
		ETSettingNewPasswdConfirm =  (EditText) findViewById(R.id.configNewPasswordConfirm);
		ETSettingHeight = (EditText) findViewById(R.id.configHeight);
		ETSettingWeight = (EditText) findViewById(R.id.configWeight);
		RGSettingSex = (RadioGroup) findViewById(R.id.config_gender);
		IBSettingSubmit = (ImageButton) findViewById(R.id.IBtab4Submit);
//		IBSettingLogout = (ImageButton) findViewById(R.id.IBtab4Logout);
		IBSettingSubmit.setOnTouchListener(this);
//		IBSettingLogout.setOnTouchListener(this);

		spinnerYear = (Spinner) findViewById(R.id.configbirthdayyear);
		spinnerMonth = (Spinner) findViewById(R.id.configbirthdaymonth);
		spinnerDay = (Spinner) findViewById(R.id.configbirthdayday);
		int year_temp = 0;
		for (int i = 0; i < intYearLength; i++) {
			year_temp = 1900 + intYearLength - 1 - i;
			year[i] = String.valueOf(year_temp);
		}

		// after the user select the option we can get value by String Text =
		// mySpinner.getSelectedItem().toString();
		adpBirthdayYear = new ArrayAdapter<String>(this,
				R.layout.spinner_style, year);
		adpBirthdayYear
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerYear.setAdapter(adpBirthdayYear);
		spinnerYear.setVisibility(View.VISIBLE);
		spinnerYear
				.setOnItemSelectedListener(new YearSpinnerSelectedListener());

		adpBirthdayMonth = new ArrayAdapter<String>(this,
				R.layout.spinner_style, month);
		adpBirthdayMonth
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerMonth.setAdapter(adpBirthdayMonth);
		spinnerMonth.setVisibility(View.VISIBLE);
		spinnerMonth
				.setOnItemSelectedListener(new MonthSpinnerSelectedListener());

		adpBirthdayDay = new ArrayAdapter<String>(this, R.layout.spinner_style,
				days);
		adpBirthdayDay
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerDay.setAdapter(adpBirthdayDay);
		spinnerDay.setVisibility(View.VISIBLE);
		spinnerDay.setOnItemSelectedListener(new DaySpinnerSelectedListener());
	}

	class MonthSpinnerSelectedListener implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			if (month[position].contains("1") || month[position].contains("3")
					|| month[position].contains("5")
					|| month[position].contains("7")
					|| month[position].contains("8")
					|| month[position].contains("10")
					|| month[position].contains("12")) {
				days = new String[] { "1日", "2日", "3日", "4日", "5日", "6日", "7日",
						"8日", "9日", "10日", "11日", "12日", "13日", "14日", "15日",
						"16日", "17日", "18日", "19日", "20日", "21日", "22日", "23日",
						"24日", "25日", "26日", "27日", "28日", "29日", "30日", "31日" };
				ArrayAdapter<String> newAdpBirthdayDay = new ArrayAdapter<String>(
						MainHomeActivity.this, R.layout.spinner_style, days);
				newAdpBirthdayDay
						.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spinnerDay.setAdapter(newAdpBirthdayDay);
			} else if (month[position].contains("2")) {
				days = new String[] { "1日", "2日", "3日", "4日", "5日", "6日", "7日",
						"8日", "9日", "10日", "11日", "12日", "13日", "14日", "15日",
						"16日", "17日", "18日", "19日", "20日", "21日", "22日", "23日",
						"24日", "25日", "26日", "27日", "28日" };
				ArrayAdapter<String> newAdpBirthdayDay = new ArrayAdapter<String>(
						MainHomeActivity.this, R.layout.spinner_style, days);
				newAdpBirthdayDay
						.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spinnerDay.setAdapter(newAdpBirthdayDay);
			} else {
				days = new String[] { "1日", "2日", "3日", "4日", "5日", "6日", "7日",
						"8日", "9日", "10日", "11日", "12日", "13日", "14日", "15日",
						"16日", "17日", "18日", "19日", "20日", "21日", "22日", "23日",
						"24日", "25日", "26日", "27日", "28日", "29日", "30日" };
				ArrayAdapter<String> newAdpBirthdayDay = new ArrayAdapter<String>(
						MainHomeActivity.this, R.layout.spinner_style, days);
				newAdpBirthdayDay
						.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spinnerDay.setAdapter(newAdpBirthdayDay);
			}
		}

		public void onNothingSelected(AdapterView<?> arg0) {

		}
	}

	class DaySpinnerSelectedListener implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
		}

		public void onNothingSelected(AdapterView<?> arg0) {

		}
	}

	class YearSpinnerSelectedListener implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			int intSelectedYear = 0;
			try {
				intSelectedYear = Integer.parseInt(spinnerYear
						.getSelectedItem().toString());
			} catch (Exception e) {
				String a = "a";
			}
			if (intSelectedYear % 400 == 0 || (intSelectedYear % 100 != 0)
					&& (intSelectedYear % 4 == 0)) {
				bLeapYear = true;
			} else {
				bLeapYear = false;
			}
			if (bLeapYear
					&& spinnerMonth.getSelectedItem().toString().contains("2")) {
				days = new String[] { "1日", "2日", "3日", "4日", "5日", "6日", "7日",
						"8日", "9日", "10日", "11日", "12日", "13日", "14日", "15日",
						"16日", "17日", "18日", "19日", "20日", "21日", "22日", "23日",
						"24日", "25日", "26日", "27日", "28日", "29日" };
				ArrayAdapter<String> newAdpBirthdayDay = new ArrayAdapter<String>(
						MainHomeActivity.this, R.layout.spinner_style, days);
				newAdpBirthdayDay
						.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spinnerDay.setAdapter(newAdpBirthdayDay);
			} else if (!bLeapYear
					&& spinnerMonth.getSelectedItem().toString().contains("2")) {
				days = new String[] { "1日", "2日", "3日", "4日", "5日", "6日", "7日",
						"8日", "9日", "10日", "11日", "12日", "13日", "14日", "15日",
						"16日", "17日", "18日", "19日", "20日", "21日", "22日", "23日",
						"24日", "25日", "26日", "27日", "28日" };
				ArrayAdapter<String> newAdpBirthdayDay = new ArrayAdapter<String>(
						MainHomeActivity.this, R.layout.spinner_style, days);
				newAdpBirthdayDay
						.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spinnerDay.setAdapter(newAdpBirthdayDay);
			}
		}

		public void onNothingSelected(AdapterView<?> arg0) {

		}
	}

	/* tab5 frame control initial,get every object pointer */
	/* rewrite tab exchange to show toast quit when user touch quit tab */
	public void QuitTabControlinit() {
		// none
	}

	public void GetFrameDataInitial() {
		int iTempCurrentTabNo = 0;
		int iTempUserInfoTabFrameSts = 0;
		int iTempMoreTableTabFrameSts = 0;
		int iTempRunningInfoTabFrameSts = 0;

		bCurrentRegisterSts = sharedPreferences.getBoolean(
				"bCurrentRegisterSts", false);

		if (false == bCurrentRegisterSts) {
			emCurrentTabNo = EM_CURRENT_TAB_NO.USERINFO;
			emUserInfoTabFrameSts = EM_USERINFO_TAB_FRAME_STS.LOGOUTTABLE;
			emMoreTableTabFrameSts = EM_MORETABLE_TAB_FRAME_STS.TIMESELECT;
			emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.DEFAULT_LISTVIEW;
			emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.DAY;
			emCurrentTableShowType = EM_TABLE_SHOW_TYPE.TIME;
			sUserID = "0";
			sSession = "0";
			MainActivitySaveFrameStsToLocal();
			iPreTabNo = EM_CURRENT_TAB_NO.USERINFO.ordinal();
			return;
		}
		emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.DEFAULT_LISTVIEW;
		emMoreTableTabFrameSts = EM_MORETABLE_TAB_FRAME_STS.TIMESELECT;
		// if bCurrentRegisterSts is true ,then emUserInfoTabFrameSts must be
		// log in
		emUserInfoTabFrameSts = EM_USERINFO_TAB_FRAME_STS.LOGINTABLE;
		emCurrentTabNo = EM_CURRENT_TAB_NO.USERINFO;
		emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.DAY;
		emCurrentTableShowType = EM_TABLE_SHOW_TYPE.TIME;
		sUserID = sharedPreferences.getString("sUserID", "0");
		sSession = sharedPreferences.getString("sSession", "0");
		iTempCurrentTabNo = sharedPreferences.getInt("emCurrentTabNo", 0);
		emCurrentTabNo = EM_CURRENT_TAB_NO.values()[iTempCurrentTabNo];

		iPreTabNo = iTempCurrentTabNo;
		switch (emCurrentTabNo) {
		case USERINFO: {
			// iTempUserInfoTabFrameSts =
			// sharedPreferences.getInt("emUserInfoTabFrameSts",0);
			// emUserInfoTabFrameSts =
			// EM_USERINFO_TAB_FRAME_STS.values()[iTempUserInfoTabFrameSts];
		}
			break;
		case MORMTABLE: {
			iTempMoreTableTabFrameSts = sharedPreferences.getInt(
					"emMoreTableTabFrameSts", 0);
			emMoreTableTabFrameSts = EM_MORETABLE_TAB_FRAME_STS.values()[iTempMoreTableTabFrameSts];
		}
			break;
		case RUNNINGINFO: {
			iTempRunningInfoTabFrameSts = sharedPreferences.getInt(
					"emRunningInfoTabFrameSts", 0);
			emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.values()[iTempRunningInfoTabFrameSts];
		}
			break;
		case SETTING: {
			emCurrentTabNo = EM_CURRENT_TAB_NO.SETTING;
		}
			break;
		default:
			break;
		}
		//
		MainActivitySaveFrameStsToLocal();
	}

	public void SetCurrentTab() {
		switch (emCurrentTabNo) {
		case USERINFO: {
			mTabHost.setCurrentTab(0);
		}
			break;
		case MORMTABLE: {
			mTabHost.setCurrentTab(1);
		}
			break;
		case RUNNINGINFO: {
			mTabHost.setCurrentTab(2);
		}
			break;
		case SETTING: {
			mTabHost.setCurrentTab(3);
		}
			break;
		default:
			break;
		}
	}

	public void RunningInfoTabDatePickerShow() {
		tab3tablerelativelayout.removeView(runninginfotableview);
		runninginfotableview = null;
		runninginfotabdatepicker.setVisibility(View.VISIBLE);

	}

	public void RunningInfoTabListViewShow() {
		tab3tablerelativelayout.removeView(runninginfotableview);

		runninginfotableview = null;

		SimpleCursorAdapter adapter = null;
		Cursor cursorListView = null;
		if (null != runninginfotableview) {
			tab3tablerelativelayout.removeView(runninginfotableview);
			runninginfotableview = null;
		}

		if (EM_RUNNINGIINFO_TAB_FRAME_STS.DEFAULT_LISTVIEW == emRunningInfoTabFrameSts) {
			cursorListView = database.get20table(this,
					Integer.parseInt(sUserID));
		} else if (EM_RUNNINGIINFO_TAB_FRAME_STS.SEARCH_LISTVIEW == emRunningInfoTabFrameSts) {
			cursorListView = database.get20tableSpecific(this, Integer
					.parseInt(sUserID), new Date(iYearRunTableUserSelect,
					iMonthsRunTableUserSelect, iDayRunTableUserSelect + 1));
		}

		if (null == cursorListView) {

			return;
		}
		int iCursorItem = cursorListView.getCount();
		if (iCursorItem > 0) {
			try {
				startManagingCursor(cursorListView);
				adapter = new SimpleCursorAdapter(this, R.layout.listview_item,
						cursorListView, new String[] { "StartTime",
								"SportTime", "Distance" }, new int[] {
								R.id.lvItemRunningTime, R.id.lvItemDurringTime,
								R.id.lvItemDurringDistance });
			} catch (Exception e) {
				e.printStackTrace();
			}

			i20TablesRunningId = new int[iCursorItem];
			for (int i = 0; i < iCursorItem; i++) {
				int index = cursorListView.getColumnIndex("RunningID");
				cursorListView.moveToNext();
				i20TablesRunningId[i] = cursorListView.getInt(index);

			}

		} else {
			// Toast.makeText(getApplicationContext(),"No Data",
			// Toast.LENGTH_LONG).show();
			if (bCurrentRegisterSts) {
				//ShowToast(getApplicationContext(), "很抱歉，没有数据");
			}
		}

		tab3listview.setAdapter(adapter);
		tab3listview.setOnItemClickListener(this);
		tab3listview.setVisibility(View.VISIBLE);
	}

	public void RunningInfoTabTableShow() {

		tab3tablerelativelayout.removeView(runninginfotableview);
		runninginfotableview = null;

		Hashtable<String, Object> hashtable = null;
		
		//totle data
		Hashtable<String, String> htTotleData = null;
		// 默认显示当天Cursor的第一条
		if (null == i20TablesRunningId) {
			Cursor cursorListView = null;
			cursorListView = database.get20table(this,
					Integer.parseInt(sUserID));
			int iCursorItem = cursorListView.getCount();
			i20TablesRunningId = new int[iCursorItem];
			for (int i = 0; i < iCursorItem; i++) {
				int index = cursorListView.getColumnIndex("RunningID");
				cursorListView.moveToNext();
				i20TablesRunningId[i] = cursorListView.getInt(index);

			}
		}
		try {
			hashtable = database.get20tableElement(Integer.parseInt(sUserID),
					this, i20TablesRunningId[i20TablesRunningIdIndex]);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		MainActivityAnalyzeHashData(hashtable);
		TextView tvRunningChartTitle = (TextView) findViewById(R.id.tab3TVtimedurring);
		tvRunningChartTitle.setText(sCurrentTableTimedurring);
		runninginfotableview = MainActivityCreateTable(
				EM_CHART_TYPE.EM_CHART_TYPE_LINE, dCurrentTableXDataArray,
				dCurrentTableYDataArray, "", "", "km/h", "跑步信息");
		try
		{
			htTotleData = database.get20tableElementInfo(this, Integer.parseInt(sUserID),i20TablesRunningId[i20TablesRunningIdIndex]);
			runninginfotabtotolesumtextview.setText("运动距离:"+htTotleData.get("Distance")
					+"公里"+";运动时间："+htTotleData.get("SportTime")+"分钟");
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		if (null != runninginfotableview) {
			RunningLineTableClickListener(runninginfotableview);
			LayoutParams tableparam = runninginfonouseview.getLayoutParams();
			runninginfotableview.setLayoutParams(tableparam);
			tab3tablerelativelayout.addView(runninginfotableview);
		}

		tab3tablerelativelayout.setVisibility(View.VISIBLE);
	}

	/* title frame initial */
	public void MainActivityTitleFrameInitial() {
		int tabId = mTabHost.getCurrentTab();
		switch (tabId) {
		// tab1
		case 0: {
			Tab1UserInfoFrameTitleinital();
			settabstyle();
		}
			break;
		// tab2
		case 1: {
			Tab2MoreTableFrameTitleinital();
			settabstyle();
		}
			break;
		// tab3
		case 2: {
			Tab3RunningInfoFrameTitleinital();
			settabstyle();
		}
			break;
		// tab4
		case 3: {
			Tab4SettingFrameTitleinital();
			settabstyle();
		}
			break;
		// tab5
		case 4: {
			// Tab5QuitFrameTitleinital();
		}
			break;
		}
	}

	public void settabstyle() {
		// set tab style
		for (int tabIndex = 0; tabIndex < mTabWidget.getChildCount(); tabIndex++) {
			final TextView tv = (TextView) mTabWidget.getChildAt(tabIndex)
					.findViewById(android.R.id.title);
			final ImageView TabViewIcon = ((ImageView) mTabWidget.getChildAt(
					tabIndex).findViewById(android.R.id.icon));
			TabViewIcon.getLayoutParams().height = 55;
			TabViewIcon.getLayoutParams().width = 50;

			tv.setTextSize(12);
			if (mTabHost.getCurrentTab() == tabIndex) {
				tv.setTextColor(this.getResources().getColorStateList(
						android.R.color.background_light));
				// tabView.setBackgroundColor(Color.rgb(15,15,15));

			} else {
				tv.setTextColor(this.getResources().getColorStateList(
						android.R.color.white));
				// tabView.setBackgroundColor(Color.rgb(23,23,23));

			}
		}
	}

	public void UserInfoTabFrameInit() {
		//get runningID arrayList
		Hashtable<String, Object> param = null;
		if(arrRunningID.size() == 0)
		{
			arrRunningID.clear();  
			int size = sharedPreferences.getInt("arrRunningIDSize", 0);    
		
			for(int i=0;i<size;i++) 
			{  
				arrRunningID.add(sharedPreferences.getString("RunningID_" + i, null));  
			}  
		}
		if(arrRunningID.size() > 0)
		{
			sRunningID = arrRunningID.get(0).toString();
		}
		else
		{
			sRunningID = "";
		}
		// save the first report showType and timeType
		EM_TABLE_ARRANGETIME_TYPE emFirstReportTimeType = EM_TABLE_ARRANGETIME_TYPE.WEEK;
		EM_TABLE_SHOW_TYPE emFirstReportShowType = EM_TABLE_SHOW_TYPE.DISTANCE;
		if (EM_CURRENT_TAB_NO.USERINFO != emCurrentTabNo) {
			return;
		}
		//add by JT
		StartFrameHandle();

		if (EM_USERINFO_TAB_FRAME_STS.LOGOUTTABLE == emUserInfoTabFrameSts) {

			// 请求周距离表
			Date dateCurrentTime = new Date(System.currentTimeMillis());
			// Date dateCurrentTime = new Date(113,0,1);
			try {
				Hashtable<String, Object> hashtable = database.getDAOChartInfo(
						dateCurrentTime, 1, 1, 0, this);
				MainActivityAnalyzeHashData(hashtable);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if ((null == sCurrentTableTimedurring) || (null == sStartTime)
					|| (null == sStopTime) || (null == dCurrentTableXDataArray)
					|| (null == dCurrentTableYDataArray)
					|| (0 == dCurrentTableYDataArray.length)) {

				if (!bCurrentRegisterSts) {
					Control con = new Control();
					double[] temp = null;
					Date tempDate = null;
				
					param = con.getOneReportByLatestTime(this);
					try
					{
						if(param.size() > 0)
						{
							if (null != param.get("iTimeType")) {
								emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.values()[(Integer) param
										.get("iTimeType")];
							} else {
								emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.DAY;
							}
							if (null != param.get("iShowType")) {
								emCurrentTableShowType = EM_TABLE_SHOW_TYPE.values()[(Integer) param
										.get("iShowType")];
							} else {
								emCurrentTableShowType = EM_TABLE_SHOW_TYPE.TIME;
							}
	
							if (null != param.get("timeBucket")) {
								sCurrentTableTimedurring = (String) param.get("timeBucket");
							}
							if (null != param.get("startTime")) {
								tempDate = (Date) param.get("startTime");
								dataStartTime = (Date) param.get("startTime");
								sStartTime = tempDate.toString();
							}
							if (null != param.get("endTime")) {
								tempDate = (Date) param.get("endTime");
								dataEndTime = (Date) param.get("endTime");
								sStopTime = tempDate.toString();
							}
							if (null != param.get("yArray")) {
								try {
									temp = (double[]) param.get("yArray");
									int aa = temp.length;
									dCurrentTableYDataArray = new double[(temp.length)];
									dCurrentTableXDataArray = new double[(temp.length)];
								} catch (Exception e) {
									e.printStackTrace();
								}
								for (int i = 0; i < (temp.length); i++) {
									if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.TIME) {
										dCurrentTableYDataArray[i] = temp[i] / 60;
									} else {
										dCurrentTableYDataArray[i] = temp[i];
									}
								}
	
								for (int i = 0; i < temp.length; i++) {
									dCurrentTableXDataArray[i] = i + 1;
								}
							}
							String allen = "";
							Tab1TableFrameTitleSet(true);
							MainActivityTitleFrameInitial();
							final GraphicalView tableview = MainActivityCreateTable(
									EM_CHART_TYPE.EM_CHART_TYPE_BAR,
									dCurrentTableXDataArray, dCurrentTableYDataArray, "",
									"", "Km", "运动距离");
							LineTableClickListener(tableview);
							tableviews.add(tableview);
							mPagerAdapter.notifyDataSetChanged();
						}
						else
						{
							ShowToast(MainHomeActivity.this, "很抱歉，没有您的运动记录，赶紧去运动吧");
							Tab1TableFrameTitleSet(false);
						}
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
				}
			} else {
				// table相关的title和时间段初始化
				Tab1TableFrameTitleSet(true);
				MainActivityTitleFrameInitial();
				final GraphicalView tableview = MainActivityCreateTable(
						EM_CHART_TYPE.EM_CHART_TYPE_BAR,
						dCurrentTableXDataArray, dCurrentTableYDataArray, "",
						"", "Km", "运动距离");
				LineTableClickListener(tableview);
				tableviews.add(tableview);
				mPagerAdapter.notifyDataSetChanged();
			}
		} else {

			// 获得所有收藏ID
			iStoreTableIdArray = database.returnAllIDs(
					Integer.parseInt(sUserID), this);
			if (null == iStoreTableIdArray) {
				Toast.makeText(getApplicationContext(), "快去运动吧！",
						Toast.LENGTH_SHORT).show();
				Tab1TableFrameTitleSet(false);
			} else {
				for (int i = 0; i < iStoreTableIdArray.length; i++) {
					Hashtable<String, Object> map = null;
					try {
						map = database.getOneReportById(iStoreTableIdArray[i],
								this);
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(map != null)
					{
						map.remove("ID");
					}
					MainActivityAnalyzeHashData(map);
					// 显示第一张的时间段和总值
					if (0 == i) {
						Tab1TableFrameTitleSet(true);
						MainActivityTitleFrameInitial();
						emFirstReportTimeType = emCurrentTableArrangeTimeType;
						emFirstReportShowType = emCurrentTableShowType;
					}
					try {
						EM_CHART_TYPE emTempChartType = EM_CHART_TYPE.EM_CHART_TYPE_LINE;
						if (emCurrentTableArrangeTimeType != EM_TABLE_ARRANGETIME_TYPE.DAY) {
							emTempChartType = EM_CHART_TYPE.EM_CHART_TYPE_BAR;
						}
						String sYAxisName = null;
						String sPromptMessage = null;
						switch (emCurrentTableShowType) {
						case TIME: {
							sYAxisName = "Minute";
							sPromptMessage = "运动时间";
						}
							break;
						case DISTANCE: {
							sYAxisName = "Km";
							sPromptMessage = "运动距离";
						}
							break;
						case CALORIE: {
							sYAxisName = "Kcal";
							sPromptMessage = "消耗卡路里";
						}
							break;
						case SPEED: {
							sYAxisName = "Km/h";
							sPromptMessage = "跑步平均速度";
						}
							break;
						default:
							break;
						}
						final GraphicalView tableview = MainActivityCreateTable(
								emTempChartType, dCurrentTableXDataArray,
								dCurrentTableYDataArray, "", "", sYAxisName,
								sPromptMessage);
						tableviews.add(tableview);
						if (emTempChartType == EM_CHART_TYPE.EM_CHART_TYPE_BAR) {
							BarTableClickListener(tableview);
						} else if (dCurrentTableXDataArray.length == 2880) {
							LineTableClickListener(tableview);
						} else {
							RunningLineTableClickListener(tableview);
						}
					} catch (Exception e) {
						Log.e(Tag, "error");
					}
				}
				iViewPagerCurrentPage = 0;
				mPagerAdapter.notifyDataSetChanged();
				emCurrentTableArrangeTimeType = emFirstReportTimeType;
				emCurrentTableShowType = emFirstReportShowType;
				//set the first report status for share weibo
				Hashtable<String, Object> map = null;
				 try {
					map = database.getOneReportById(iStoreTableIdArray[0], this);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(map != null)
				{
					map.remove("ID");
				}
				MainActivityAnalyzeHashData(map);
			}

		}
	}

	/* more table tab frame show initial */
	public void MoreTableTabFrameInit() {
		if (EM_CURRENT_TAB_NO.MORMTABLE != emCurrentTabNo) {
			return;
		}

		layoutTab2TimeView.setVisibility(View.GONE);
		layoutTab2UserTypeSelect.setVisibility(View.GONE);
		layoutTab2Table.setVisibility(View.GONE);
		layoutTab2MoreReportText.setVisibility(View.GONE);
		if (null != moretabletableview) {
			layoutTab2Table.removeView(moretabletableview);
			moretabletableview = null;
		}
		switch (emMoreTableTabFrameSts) {
		case TIMESELECT: {
			layoutTab2TimeView.setVisibility(View.VISIBLE);
			layoutTab2UserTypeSelect.setVisibility(View.VISIBLE);
			layoutTab2MoreReportText.setVisibility(View.VISIBLE);
			// set default
			emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.DAY;
			emCurrentTableShowType = EM_TABLE_SHOW_TYPE.TIME;
		}
			break;
		case TABLETIME:
		case TABLEDISTANCE:
		case TABLECALORIE:
		case TABLESPEED: {
			layoutTab2Table.setVisibility(View.VISIBLE);
			// tables handle
			Date date = new Date(iYearUserSelect, iMonthsUserSelect,
					iDayUserSelect + 1);
			CheckCurrentRadioShowType();
			Hashtable<String, Object> hashtable = null;
			try {
				
				hashtable = database.getDAOChartInfo(date,
						emCurrentTableShowType.ordinal(),
						emCurrentTableArrangeTimeType.ordinal(),
						Integer.parseInt(sUserID), this);

			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			MainActivityAnalyzeHashData(hashtable);
			if ((null == sCurrentTableTimedurring) || (null == sStartTime)
					|| (null == sStopTime) || (null == dCurrentTableXDataArray)
					|| (null == dCurrentTableYDataArray)
					|| (0 == dCurrentTableYDataArray.length)) {
				Tab2TableFrameTitleSet(false);

				ShowToast(MainHomeActivity.this, "很抱歉，没有数据");
			} else {
				Tab2TableFrameTitleSet(true);

				if (EM_TABLE_ARRANGETIME_TYPE.DAY == emCurrentTableArrangeTimeType) {
					if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.TIME) {
						moretabletableview = MainActivityCreateTable(
								EM_CHART_TYPE.EM_CHART_TYPE_LINE,
								dCurrentTableXDataArray,
								dCurrentTableYDataArray, "", "", "Minute",
								"运动时间");
					} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.DISTANCE) {
						moretabletableview = MainActivityCreateTable(
								EM_CHART_TYPE.EM_CHART_TYPE_LINE,
								dCurrentTableXDataArray,
								dCurrentTableYDataArray, "", "", "Km", "运动距离");
					} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.CALORIE) {
						moretabletableview = MainActivityCreateTable(
								EM_CHART_TYPE.EM_CHART_TYPE_LINE,
								dCurrentTableXDataArray,
								dCurrentTableYDataArray, "", "", "Kcal",
								"消耗卡路里");
					} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.SPEED) {
						moretabletableview = MainActivityCreateTable(
								EM_CHART_TYPE.EM_CHART_TYPE_LINE,
								dCurrentTableXDataArray,
								dCurrentTableYDataArray, "", "", "Km/h",
								"跑步平均速度");
					}
				} else {
					if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.TIME) {
						moretabletableview = MainActivityCreateTable(
								EM_CHART_TYPE.EM_CHART_TYPE_BAR,
								dCurrentTableXDataArray,
								dCurrentTableYDataArray, "", "", "Minute",
								"运动时间");
					} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.DISTANCE) {
						moretabletableview = MainActivityCreateTable(
								EM_CHART_TYPE.EM_CHART_TYPE_BAR,
								dCurrentTableXDataArray,
								dCurrentTableYDataArray, "", "", "Km", "运动距离");
					} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.CALORIE) {
						moretabletableview = MainActivityCreateTable(
								EM_CHART_TYPE.EM_CHART_TYPE_BAR,
								dCurrentTableXDataArray,
								dCurrentTableYDataArray, "", "", "Kcal",
								"消耗卡路里");
					} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.SPEED) {
						moretabletableview = MainActivityCreateTable(
								EM_CHART_TYPE.EM_CHART_TYPE_BAR,
								dCurrentTableXDataArray,
								dCurrentTableYDataArray, "", "", "Km/h",
								"跑步平均速度");
					}
				}
				if (null != moretabletableview) {
					if (EM_TABLE_ARRANGETIME_TYPE.DAY == emCurrentTableArrangeTimeType) {
						LineTableClickListener(moretabletableview);
					} else {
						BarTableClickListener(moretabletableview);
					}
					LayoutParams tableparam = moretablenouseview
							.getLayoutParams();
					moretabletableview.setLayoutParams(tableparam);
					layoutTab2Table.addView(moretabletableview);
				}
			}

		}
			break;
		default:
			break;

		}
	}

	public void RunningInfoTabFrameInit() {
		if (EM_CURRENT_TAB_NO.RUNNINGINFO != emCurrentTabNo) {
			return;
		}
		runninginfotabdatepicker.setVisibility(View.GONE);
		tab3listview.setVisibility(View.GONE);
		tab3tablerelativelayout.setVisibility(View.GONE);

		if (EM_RUNNINGIINFO_TAB_FRAME_STS.TIME == emRunningInfoTabFrameSts) {
			RunningInfoTabDatePickerShow();
		} else if (EM_RUNNINGIINFO_TAB_FRAME_STS.DEFAULT_LISTVIEW == emRunningInfoTabFrameSts) {
			RunningInfoTabListViewShow();
		} else if (EM_RUNNINGIINFO_TAB_FRAME_STS.SEARCH_LISTVIEW == emRunningInfoTabFrameSts) {
			RunningInfoTabListViewShow();
		} else {
			RunningInfoTabTableShow();
		}
	}

	public void SettingTabFrameInit() {
		if (EM_CURRENT_TAB_NO.SETTING != emCurrentTabNo) {
			return;
		}
		// 已经请求过了
		if (true == bSettingReqUserInfoFlag) {
			return;
		}
		// get the user info
		String strUserEmail = sharedPreferences.getString("sUserName", "");
		String strUserPassword = sharedPreferences.getString("sUserPassword",
				"");
		SettingTabThreadDataReq(strUserEmail, strUserPassword);
		// show dialog
		progdialogSettingGetUserInfo = ProgressDialog.show(
				MainHomeActivity.this, "正在加载", "系统正在获取用户数据");
	}

	public void SettingTabFrameShow() {
		String strUserEmail = sharedPreferences.getString("sUserName", "");
		String strUserPassword = sharedPreferences.getString("sUserPassword",
				"");
		strSex = getUserInfo.getAsString("User_Gender");
		strUserHeight = getUserInfo.getAsString("User_Height");
		strUserWeight = getUserInfo.getAsString("User_Weight");
		strUserbirthday = getUserInfo.getAsString("User_Birthday");
		if (strUserbirthday != null && strUserbirthday.length() > 0) {
			String[] UserBirthday_Temp = strUserbirthday.split("-");
			if (UserBirthday_Temp.length > 2) {
				strUserYear = UserBirthday_Temp[0];
				strUserMonth = UserBirthday_Temp[1];
				strUserDay = UserBirthday_Temp[2];
			}
		}
		if (strSex != null && strSex.toLowerCase().equals("m")) {
			strSex = "female";
		} else if (strSex != null && strSex.toLowerCase().equals("f")) {
			strSex = "male";
		}
		ETSettingEmail.setText(strUserEmail);
		ETSettingHeight.setText(strUserHeight);
		ETSettingWeight.setText(strUserWeight);
		if (strSex == "female") {
			RGSettingSex.check(R.id.configBoy);
		} else {
			RGSettingSex.check(R.id.configGirl);
		}
		if (strUserYear != null && strUserYear.length() > 0) {
			spinnerYear.setSelection(intCurrentYear
					- Integer.parseInt(strUserYear));
		}
		if (strUserMonth != null && strUserMonth.length() > 0) {
			spinnerMonth.setSelection(Integer.parseInt(strUserMonth) - 1);
		}
		if (strUserDay != null && strUserDay.length() > 0) {
			spinnerDay.setSelection(Integer.parseInt(strUserDay) - 1);
		}
	}

	/* quit tab frame initial */
	/* initial the quit dialog when user click this tab */
	public void QuitTabFrameInit() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("提示");
		builder.setMessage("是否退出后还在后台运行运动令？");
		builder.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub、
						//save runningID arraylist    		    
//					    editor.putInt("arrRunningIDSize", arrRunningID.size());
//					    for(int i=0;i<arrRunningID.size();i++)
//					    {
//					    	editor.remove("RunningID_" + i);  
//					    	editor.putString("RunningID_" + i, arrRunningID.get(i).toString());  
//					    }
//					    editor.commit();
						bDestoryApp = true;
						arg0.dismiss();
						MainHomeActivity.this.finish();
					}
				});
		builder.setNegativeButton("退出",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						//save runningID arraylist 
//					    editor.putInt("arrRunningIDSize", arrRunningID.size());
//					    for(int i=0;i<arrRunningID.size();i++)
//					    {
//					    	editor.remove("RunningID_" + i);  
//					    	editor.putString("RunningID_" + i, arrRunningID.get(i).toString());  
//					    }
//					    editor.commit();
						bDestoryApp = true;
						arg0.dismiss();
						MainActivityEndService();
						// log off status
						bCurrentRegisterSts = false;
						MainActivitySaveFrameStsToLocal();
						MainHomeActivity.this.finish();
						//System.exit(0);
					}
				});
		builder.setNeutralButton("取消",
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}

				});
		builder.create().show();
	}

	@Override
	public void onDestroy() {
		YDLApplication YDLApplication = (YDLApplication) getApplication();
		YDLApplication.setDecreaseNum();
		try {
			if (bDestoryApp) {
				super.onDestroy();
				System.exit(0);
			} else {
				super.onDestroy();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.exit(0); 
		}
	}

	/* every tab frame show function */
	public void Tab1UserInfoFrameTitleinital() {

		userinfotabtitleleftbutton.setVisibility(View.GONE);
		userinfotabtitlerightbutton.setBackgroundResource(R.drawable.share);
		userinfotabtitlerightbutton.setVisibility(View.VISIBLE);
		if (EM_USERINFO_TAB_FRAME_STS.LOGOUTTABLE == emUserInfoTabFrameSts) {
			// set the page title
			titlename.setText("运动时间"+GetLoginName());

		} else {
			switch (emCurrentTableShowType)// EM_TABLE_SHOW_TYPE
			{
			case TIME: {
				titlename.setText("时间"+GetLoginName());
			}
				break;
			case DISTANCE: {
				titlename.setText("距离"+GetLoginName());
			}
				break;
			case CALORIE: {
				titlename.setText("卡路里"+GetLoginName());
			}
				break;
			case SPEED: {
				titlename.setText("速度"+GetLoginName());
			}
				break;
			default:
				break;

			}
		}
	}

	public void Tab2MoreTableFrameTitleinital() {
		// Initial the tab2,set the element show and hidden
		switch (emMoreTableTabFrameSts) {
		case TIMESELECT: {
			titlename.setText("时间选择"+GetLoginName());
			userinfotabtitleleftbutton.setVisibility(View.GONE);
			userinfotabtitlerightbutton
					.setBackgroundResource(R.drawable.confirm);
			userinfotabtitlerightbutton.setVisibility(View.VISIBLE);
		}
			break;
		case TABLETIME: {
			titlename.setText("运动时间"+GetLoginName());
			userinfotabtitleleftbutton.setBackgroundResource(R.drawable.back);
			userinfotabtitleleftbutton.setVisibility(View.VISIBLE);
			userinfotabtitlerightbutton.setBackgroundResource(R.drawable.share);
			userinfotabtitlerightbutton.setVisibility(View.VISIBLE);
		}
			break;
		case TABLEDISTANCE: {
			titlename.setText("运动距离"+GetLoginName());
			userinfotabtitleleftbutton.setBackgroundResource(R.drawable.back);
			userinfotabtitleleftbutton.setVisibility(View.VISIBLE);
			userinfotabtitlerightbutton.setBackgroundResource(R.drawable.share);
			userinfotabtitlerightbutton.setVisibility(View.VISIBLE);
		}
			break;
		case TABLECALORIE: {
			titlename.setText("卡路里"+GetLoginName());
			userinfotabtitleleftbutton.setBackgroundResource(R.drawable.back);
			userinfotabtitleleftbutton.setVisibility(View.VISIBLE);
			userinfotabtitlerightbutton.setBackgroundResource(R.drawable.share);
			userinfotabtitlerightbutton.setVisibility(View.VISIBLE);
		}
			break;
		case TABLESPEED: {
			titlename.setText("运动速度"+GetLoginName());
			userinfotabtitleleftbutton.setBackgroundResource(R.drawable.back);
			userinfotabtitleleftbutton.setVisibility(View.VISIBLE);
			userinfotabtitlerightbutton.setBackgroundResource(R.drawable.share);
			userinfotabtitlerightbutton.setVisibility(View.VISIBLE);
		}
			break;
		default:
			break;
		}
	}

	public void Tab3RunningInfoFrameTitleinital() {
		// initial the tab3 information
		if (EM_RUNNINGIINFO_TAB_FRAME_STS.TIME == emRunningInfoTabFrameSts) {
			titlename.setText("选择时间"+GetLoginName());
			userinfotabtitleleftbutton.setVisibility(View.VISIBLE);
			userinfotabtitleleftbutton.setBackgroundResource(R.drawable.back);
			userinfotabtitlerightbutton
					.setBackgroundResource(R.drawable.confirm);
			userinfotabtitlerightbutton.setVisibility(View.VISIBLE);
		} else if (EM_RUNNINGIINFO_TAB_FRAME_STS.DEFAULT_LISTVIEW == emRunningInfoTabFrameSts) {
			titlename.setText("跑步清单"+GetLoginName());
			userinfotabtitleleftbutton.setVisibility(View.GONE);
			userinfotabtitlerightbutton
					.setBackgroundResource(R.drawable.more);
			userinfotabtitlerightbutton.setVisibility(View.VISIBLE);

		} else if (EM_RUNNINGIINFO_TAB_FRAME_STS.SEARCH_LISTVIEW == emRunningInfoTabFrameSts) {
			titlename.setText("跑步清单"+GetLoginName());
			userinfotabtitleleftbutton.setBackgroundResource(R.drawable.back);
			userinfotabtitleleftbutton.setVisibility(View.VISIBLE);
			userinfotabtitlerightbutton.setVisibility(View.GONE);
		} else {
			titlename.setText("跑步图表"+GetLoginName());
			userinfotabtitleleftbutton.setBackgroundResource(R.drawable.back);
			userinfotabtitleleftbutton.setVisibility(View.VISIBLE);
			userinfotabtitlerightbutton.setVisibility(View.GONE);
		}

	}

	public void Tab4SettingFrameTitleinital() {
		titlename.setText("设置"+GetLoginName());
		userinfotabtitleleftbutton.setVisibility(View.GONE);
		userinfotabtitlerightbutton.setVisibility(View.GONE);
	}

	public void Tab5QuitFrameTitleinital() {
		titlename.setText("退出");
		userinfotabtitleleftbutton.setVisibility(View.GONE);
		userinfotabtitlerightbutton.setVisibility(View.GONE);
	}

	public void onTitleTouchHandle(int iTouchKind, int touchId) {

		if ((R.id.TitleLeftButton != touchId)
				&& (R.id.TitleRightButton != touchId)) {
			return;
		}

		if ((MotionEvent.ACTION_DOWN != iTouchKind)
				&& (MotionEvent.ACTION_UP != iTouchKind)) {
			return;
		}
		int tabId = mTabHost.getCurrentTab();
		switch (tabId) {

		case 0: {
			if (R.id.TitleLeftButton == touchId) {
				/* not exist */
				return;
			} else {
				if (MotionEvent.ACTION_DOWN == iTouchKind) {
					userinfotabtitlerightbutton
							.setBackgroundResource(R.drawable.share_click);
				} else {
					userinfotabtitlerightbutton
							.setBackgroundResource(R.drawable.share);

					/* login logic status */
					if (EM_USERINFO_TAB_FRAME_STS.LOGINTABLE == emUserInfoTabFrameSts) {
						if (null == tableviews || 0 == tableviews.size()) {
							ShowToast(getApplicationContext(), "无法操作");
						} else {
							GraphicalView viewTemp = tableviews
									.get(iViewPagerCurrentPage);
							Control con = new Control();
							String strStartTime = "";
							String strEndTime = "";
							Timestamp tsStart = new Timestamp(dataStartTime.getTime());
							strStartTime = tsStart.toString();
							tsStart = new Timestamp(dataEndTime.getTime()); 
							strEndTime = tsStart.toString(); 
							String strShareMessage = con.getWeiboInfo(sUserID,sSessionID,emCurrentTableArrangeTimeType.ordinal(),"1",strStartTime,strEndTime,emCurrentTableShowType.ordinal(),this,sRunningID);						
							new YDLWeiBoShare(this, viewTemp,strShareMessage).onShare();
						}
					} else {
						ShowToast(getApplicationContext(), "请先登入");
					}
				}
			}
		}
			break;
		case 1: {
			if (R.id.TitleLeftButton == touchId) {
				if (EM_MORETABLE_TAB_FRAME_STS.TIMESELECT == emMoreTableTabFrameSts) {
					return;
				} else {
					if (MotionEvent.ACTION_DOWN == iTouchKind) {
						userinfotabtitleleftbutton
								.setBackgroundResource(R.drawable.back_click);
					} else {
						userinfotabtitleleftbutton
								.setBackgroundResource(R.drawable.back_click);
						emMoreTableTabFrameSts = EM_MORETABLE_TAB_FRAME_STS.TIMESELECT;
						MoreTableTabFrameInit();
						Tab2MoreTableFrameTitleinital();
					}
				}
			} else {
				if (EM_MORETABLE_TAB_FRAME_STS.TIMESELECT == emMoreTableTabFrameSts) {
					if (MotionEvent.ACTION_DOWN == iTouchKind) {
						userinfotabtitlerightbutton
								.setBackgroundResource(R.drawable.confirm_click);
					} else {
						userinfotabtitlerightbutton
								.setBackgroundResource(R.drawable.confirm);

						Tab2SearchThreadHandle();

					}
				} else {
					// share button handle
					if (MotionEvent.ACTION_DOWN == iTouchKind) {
						userinfotabtitlerightbutton
								.setBackgroundResource(R.drawable.share_click);
					} else {
						userinfotabtitlerightbutton
								.setBackgroundResource(R.drawable.share);
						if (null == moretabletableview) {
							ShowToast(getApplicationContext(), "无法分享");
						} else {
							Control con = new Control();
							String strStartTime = "";
							String strEndTime = "";
							Timestamp tsStart = new Timestamp(dataStartTime.getTime());
							strStartTime = tsStart.toString();
							tsStart = new Timestamp(dataEndTime.getTime()); 
							strEndTime = tsStart.toString(); 
							String strShareMessage = con.getWeiboInfo(sUserID,sSessionID,emCurrentTableArrangeTimeType.ordinal(),"1",strStartTime,strEndTime,emCurrentTableShowType.ordinal(),this,"");
							new YDLWeiBoShare(this, moretabletableview,strShareMessage)
									.onShare();
						}
					}
				}
			}
		}
			break;
		case 2: {
			if (R.id.TitleLeftButton == touchId) {
				if (EM_RUNNINGIINFO_TAB_FRAME_STS.SEARCH_LISTVIEW == emRunningInfoTabFrameSts) {
					if (MotionEvent.ACTION_DOWN == iTouchKind) {
						userinfotabtitleleftbutton
								.setBackgroundResource(R.drawable.back_click);
					} else {
						userinfotabtitleleftbutton
								.setBackgroundResource(R.drawable.back);
						// back to date picker
						emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.TIME;
						// Tab3RunningInfoFrameTitleinital();
						// RunningInfoTabFrameInit();
						tab3SearchThreadHandle();
					}
				} else if (EM_RUNNINGIINFO_TAB_FRAME_STS.TABLE == emRunningInfoTabFrameSts) {
					if (MotionEvent.ACTION_DOWN == iTouchKind) {
						userinfotabtitleleftbutton
								.setBackgroundResource(R.drawable.back_click);
					} else {
						userinfotabtitleleftbutton
								.setBackgroundResource(R.drawable.back);
						// back to list view
						if (true == bRunningInfoTableFromDefaultListview) {
							emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.DEFAULT_LISTVIEW;
						} else {
							emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.SEARCH_LISTVIEW;
						}
						// 增加处理
						// Tab3RunningInfoFrameTitleinital();
						// //RunningInfoTabFrameInit();
						tab3SearchThreadHandle();
					}
				} else if (EM_RUNNINGIINFO_TAB_FRAME_STS.TIME == emRunningInfoTabFrameSts) {
					if (MotionEvent.ACTION_DOWN == iTouchKind) {
						userinfotabtitleleftbutton
								.setBackgroundResource(R.drawable.back_click);
					} else {
						userinfotabtitleleftbutton
								.setBackgroundResource(R.drawable.back);
						// go to change time page
						emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.DEFAULT_LISTVIEW;
						// Tab3RunningInfoFrameTitleinital();
						// RunningInfoTabFrameInit();
						tab3SearchThreadHandle();
					}
				} else {
					return;
				}
			} else {
				if (EM_RUNNINGIINFO_TAB_FRAME_STS.TIME == emRunningInfoTabFrameSts) {
					if (MotionEvent.ACTION_DOWN == iTouchKind) {
						userinfotabtitlerightbutton
								.setBackgroundResource(R.drawable.confirm_click);
					} else {
						userinfotabtitlerightbutton
								.setBackgroundResource(R.drawable.confirm);
						// go to list view
						emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.SEARCH_LISTVIEW;
						// Tab3RunningInfoFrameTitleinital();
						// RunningInfoTabFrameInit();
						tab3SearchThreadHandle();
					}
				} else if (EM_RUNNINGIINFO_TAB_FRAME_STS.DEFAULT_LISTVIEW == emRunningInfoTabFrameSts) {
					if (MotionEvent.ACTION_DOWN == iTouchKind) {
						userinfotabtitlerightbutton
								.setBackgroundResource(R.drawable.more_click);
					} else {
						userinfotabtitlerightbutton
								.setBackgroundResource(R.drawable.more);
						// go to change time page
						emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.TIME;
						// Tab3RunningInfoFrameTitleinital();
						// RunningInfoTabFrameInit();
						tab3SearchThreadHandle();
					}
				}
			}
		}
			break;
		case 3: {
			// unknown
		}
			break;
		case 4: {
			// unknown
		}
			break;
		}
	}

	@Override
	public void onTabChanged(String tabid) {
		// TODO Auto-generated method stub
		Log.e(Tag, "Tab Change");
		int tabId = mTabHost.getCurrentTab();
		if (false == bCurrentRegisterSts) {
			if (4 == tabId) {
				QuitTabFrameInit();
				bQuitDialog = true;
				mTabHost.setCurrentTab(0);
			} else {
				if (true == bQuitDialog) {
					bQuitDialog = false;
					return;
				}

				if (false == bUnregTabChange) {
					bUnregTabChange = true;
					emCurrentTabNo = EM_CURRENT_TAB_NO.USERINFO;
					iPreTabNo = 0;
					MainActivitySaveFrameStsToLocal();
					MainHomeActivity.this.finish();
					Intent intent = new Intent();
					intent.setClass(this, UserLoginActivity.class);
					this.startActivity(intent);
					mTabHost.setCurrentTab(0);

				}

			}
			// mTabHost.setCurrentTab(0);
			// emCurrentTabNo = EM_CURRENT_TAB_NO.values()[0];
			// iPreTabNo = 0;
			// MainActivitySaveFrameStsToLocal();
		} else {
			if (4 == tabId) {
				QuitTabFrameInit();
				IsQuit = true;
				mTabHost.setCurrentTab(emCurrentTabNo.ordinal());
				return;
			} else {
				iPreTabNo = emCurrentTabNo.ordinal();
				emCurrentTabNo = EM_CURRENT_TAB_NO.values()[tabId];
				// mTabHost.setCurrentTab(emCurrentTabNo.ordinal());
				// set the tab state when user click the tab
				if (emCurrentTabNo == EM_CURRENT_TAB_NO.MORMTABLE) {
					emMoreTableTabFrameSts = EM_MORETABLE_TAB_FRAME_STS.TIMESELECT;
				} else if (emCurrentTabNo == EM_CURRENT_TAB_NO.RUNNINGINFO) {
					emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.DEFAULT_LISTVIEW;
				}
				// title frame change
				if(!IsQuit)
				{
					MainActivityTitleFrameInitial();
				}
				if (true == bFirstAppRunn) {
					bFirstAppRunn = false;
					UserInfoTabFrameInit();
				}
				
				if(0 == tabId)
				{
					Hashtable<String, Object> map = null;
					 try {
						map = database.getOneReportById(iStoreTableIdArray[iViewPagerCurrentPage], this);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(map != null)
					{
						map.remove("ID");
					}
					MainActivityAnalyzeHashData(map);
					if(arrRunningID.size() > 0)
					{
						sRunningID = arrRunningID.get(0).toString();
					}
					else
					{
						sRunningID = "";
					}
				}
				if(!IsQuit)
				{
					MoreTableTabFrameInit();
					RunningInfoTabFrameInit();
					tab3SearchThreadHandle();
					SettingTabFrameInit();
					// save the frame state
					MainActivitySaveFrameStsToLocal();
				}
				else
				{
					IsQuit = false;
				}
			}

		}

	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		// TODO Auto-generated method stub
		boolean bRet = false;
		int id = arg0.getId();
		int iTouchKind = MotionEvent.ACTION_MASK;
		switch (arg1.getAction()) {
		case MotionEvent.ACTION_DOWN:
			iTouchKind = MotionEvent.ACTION_DOWN;
			break;
		case MotionEvent.ACTION_UP:
			iTouchKind = MotionEvent.ACTION_UP;
		default:
			break;
		}
		switch (id) {
		case R.id.TitleLeftButton: {

			if (MotionEvent.ACTION_DOWN == iTouchKind) {
				Log.e(Tag, "left button touchdown");
			} else if (MotionEvent.ACTION_UP == iTouchKind) {

				new YDLButtonSound(this);
				Log.e(Tag, "left button touchup");
			}
		}
			break;
		case R.id.TitleRightButton: {
			if (MotionEvent.ACTION_DOWN == iTouchKind) {
				Log.e(Tag, "right button touchdown");
			} else if (MotionEvent.ACTION_UP == iTouchKind) {
				new YDLButtonSound(this);
				Log.e(Tag, "right button touchup");
			}

		}
			break;
		case R.id.tab1IBdeletetable: {
			if (MotionEvent.ACTION_DOWN == iTouchKind) {
				imagebuttonUserInfoDeleteTable
						.setBackgroundResource(R.drawable.removereport_click);
				Log.e(Tag, "delete table button touchdown");
			} else if (MotionEvent.ACTION_UP == iTouchKind) {
				imagebuttonUserInfoDeleteTable
						.setBackgroundResource(R.drawable.deletereport);
				new YDLButtonSound(this);
				Log.e(Tag, "delete table button touchup");
				if ((false == bCurrentRegisterSts)) {
					ShowToast(getApplicationContext(), "请登录后在进行操作");
				} else if (1 == tableviews.size()) {
					ShowToast(getApplicationContext(), "很抱歉，请至少保留一张报表");
				} else if (0 == tableviews.size()) {
					ShowToast(getApplicationContext(), "很抱歉，没有可以删除的报表");
				} else {
					tableviews.remove(iViewPagerCurrentPage);
					mPagerAdapter.notifyDataSetChanged();
					database.deleteOneReport(
							iStoreTableIdArray[iViewPagerCurrentPage], this);
					iStoreTableIdArray = database.returnAllIDs(
							Integer.parseInt(sUserID), this);
					arrRunningID.remove(iViewPagerCurrentPage);
				}

			}
		}
			break;
		case R.id.IBfavorite: {
			if (MotionEvent.ACTION_DOWN == iTouchKind) {
				moretabletabfavoratebutton
						.setBackgroundResource(R.drawable.savereport_click);
				Log.e(Tag, "favorite table button touchdown");
			} else if (MotionEvent.ACTION_UP == iTouchKind) {
				moretabletabfavoratebutton
						.setBackgroundResource(R.drawable.savereport);
				new YDLButtonSound(this);
				Log.e(Tag, "favorite table button touchup");

				CheckCurrentRadioShowType();
				Date date = new Date(iYearUserSelect, iMonthsUserSelect,
						iDayUserSelect + 1);
				Hashtable<String, Object> hashtable = null;
				try {
					hashtable = database.getDAOChartInfo(date,
							emCurrentTableShowType.ordinal(),
							emCurrentTableArrangeTimeType.ordinal(),
							Integer.parseInt(sUserID), this);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				MainActivityAnalyzeHashData(hashtable);

				if ((null == sCurrentTableTimedurring) || (null == sStartTime)
						|| (null == sStopTime)
						|| (null == dCurrentTableXDataArray)
						|| (null == dCurrentTableYDataArray)
						|| (0 == dCurrentTableYDataArray.length)) {
					ShowToast(MainHomeActivity.this, "对不起，该报表不能收藏");
				} else {

					if (0 == tableviews.size()) {
						Tab1TableFrameTitleSet(true);
					}
					GraphicalView tableview = null;
					if (EM_TABLE_ARRANGETIME_TYPE.DAY == emCurrentTableArrangeTimeType) {
						if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.TIME) {
							tableview = MainActivityCreateTable(
									EM_CHART_TYPE.EM_CHART_TYPE_LINE,
									dCurrentTableXDataArray,
									dCurrentTableYDataArray, "", "", "Minute",
									"运动时间");
						} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.DISTANCE) {
							tableview = MainActivityCreateTable(
									EM_CHART_TYPE.EM_CHART_TYPE_LINE,
									dCurrentTableXDataArray,
									dCurrentTableYDataArray, "", "", "Km",
									"运动距离");
						} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.CALORIE) {
							tableview = MainActivityCreateTable(
									EM_CHART_TYPE.EM_CHART_TYPE_LINE,
									dCurrentTableXDataArray,
									dCurrentTableYDataArray, "", "", "Kcal",
									"消耗卡路里");
						} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.SPEED) {
							tableview = MainActivityCreateTable(
									EM_CHART_TYPE.EM_CHART_TYPE_LINE,
									dCurrentTableXDataArray,
									dCurrentTableYDataArray, "", "", "Km/h",
									"跑步平均速度");
						}
						LineTableClickListener(tableview);
					} else {
						if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.TIME) {
							tableview = MainActivityCreateTable(
									EM_CHART_TYPE.EM_CHART_TYPE_BAR,
									dCurrentTableXDataArray,
									dCurrentTableYDataArray, "", "", "Minute",
									"运动时间");
						} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.DISTANCE) {
							tableview = MainActivityCreateTable(
									EM_CHART_TYPE.EM_CHART_TYPE_BAR,
									dCurrentTableXDataArray,
									dCurrentTableYDataArray, "", "", "Km",
									"运动距离");
						} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.CALORIE) {
							tableview = MainActivityCreateTable(
									EM_CHART_TYPE.EM_CHART_TYPE_BAR,
									dCurrentTableXDataArray,
									dCurrentTableYDataArray, "", "", "Kcal",
									"消耗卡路里");
						} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.SPEED) {
							tableview = MainActivityCreateTable(
									EM_CHART_TYPE.EM_CHART_TYPE_BAR,
									dCurrentTableXDataArray,
									dCurrentTableYDataArray, "", "", "Km/h",
									"跑步平均速度");
						}
						BarTableClickListener(tableview);
					}
					tableviews.add(tableview);
					mPagerAdapter.notifyDataSetChanged();
					int iNewTableID = database.storeReport(this, dataStartTime,
							dataEndTime,
							emCurrentTableArrangeTimeType.ordinal(),
							Integer.parseInt(sUserID),
							emCurrentTableShowType.ordinal());
					// Toast.makeText(MainHomeActivity.this,
					// "Favorite Data Success", Toast.LENGTH_LONG).show();
					if (-1 == iNewTableID) {
						ShowToast(this, "收藏失败");
					} else {
						arrRunningID.add("");
						iStoreTableIdArray = database.returnAllIDs(
								Integer.parseInt(sUserID), this);
						ShowToast(MainHomeActivity.this, "收藏成功");
					    editor.putInt("arrRunningIDSize", arrRunningID.size());
					    for(int i=0;i<arrRunningID.size();i++)
					    {
					    	editor.remove("RunningID_" + i);  
					    	editor.putString("RunningID_" + i, arrRunningID.get(i).toString());  
					    }
					    editor.commit();
					}
				}
			}
		}
			break;
		case R.id.IBtab4Submit: {
			if (MotionEvent.ACTION_DOWN == iTouchKind) {
				IBSettingSubmit.setBackgroundResource(R.drawable.submit_click);
				Log.e(Tag, "setting submit button touchdown");
			} else if (MotionEvent.ACTION_UP == iTouchKind) {
				IBSettingSubmit.setBackgroundResource(R.drawable.submit);
				new YDLButtonSound(this);
				Log.e(Tag, "setting submit button touchup");
				SettingTabSubmitInfoHandle();
			}
		}
			break;
//		case R.id.IBtab4Logout: {
//			if (MotionEvent.ACTION_DOWN == iTouchKind) {
//				IBSettingLogout.setBackgroundResource(R.drawable.logout_click);
//				Log.e(Tag, "setting submit button touchdown");
//			} else if (MotionEvent.ACTION_UP == iTouchKind) {
//				IBSettingLogout.setBackgroundResource(R.drawable.logout);
//				new YDLButtonSound(this);
//				Log.e(Tag, "setting submit button touchup");
//			}
//		}
//			break;
		case R.id.tab3IBfavorite: {
			int RunningIDTemp = 0;
			if (MotionEvent.ACTION_DOWN == iTouchKind) {
				tab3tablefavorate
						.setBackgroundResource(R.drawable.savereport_click);
				Log.e(Tag, "tab3 favorite table button touchdown");
			} else if (MotionEvent.ACTION_UP == iTouchKind) {
				tab3tablefavorate.setBackgroundResource(R.drawable.savereport);
				new YDLButtonSound(this);
				Log.e(Tag, "tab3 favorite table button touchup");
				// save table handle
				Hashtable<String, Object> hashtable = null;
				try {
					hashtable = database.get20tableElement(
							Integer.parseInt(sUserID), this,
							i20TablesRunningId[i20TablesRunningIdIndex]);
				    RunningIDTemp = i20TablesRunningId[i20TablesRunningIdIndex];
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				MainActivityAnalyzeHashData(hashtable);
				GraphicalView tableview = null;

				tableview = MainActivityCreateTable(
						EM_CHART_TYPE.EM_CHART_TYPE_LINE,
						dCurrentTableXDataArray, dCurrentTableYDataArray, "",
						"", "Km/h", "跑步记录");

				RunningLineTableClickListener(tableview);
				tableviews.add(tableview);
				mPagerAdapter.notifyDataSetChanged();
				int iNewTableID = database.storeReport(this, dataStartTime,
						dataEndTime, emCurrentTableArrangeTimeType.ordinal(),
						Integer.parseInt(sUserID),
						emCurrentTableShowType.ordinal());
				// Toast.makeText(MainHomeActivity.this,
				// "Favorite Data Success", Toast.LENGTH_LONG).show();

				if (-1 == iNewTableID) {
					ShowToast(MainHomeActivity.this, "收藏失败");
				} else {
					iStoreTableIdArray = database.returnAllIDs(
							Integer.parseInt(sUserID), this);
					ShowToast(MainHomeActivity.this, "收藏成功");
					arrRunningID.add(String.valueOf(RunningIDTemp));
				    editor.putInt("arrRunningIDSize", arrRunningID.size());
				    for(int i=0;i<arrRunningID.size();i++)
				    {
				    	editor.remove("RunningID_" + i);  
				    	editor.putString("RunningID_" + i, arrRunningID.get(i).toString());  
				    }
				    editor.commit();
				}
			}
		}
			break;
		default:
			break;
		}

		onTitleTouchHandle(iTouchKind, id);
		// save
		MainActivitySaveFrameStsToLocal();
		return bRet;
	}

	@Override
	public void onCheckedChanged(RadioGroup arg0, int arg1) {
		// TODO Auto-generated method stub
		int RadioGroupId = arg0.getId();
		if (R.id.radiogroupdate == RadioGroupId) {
			switch (arg1) {
			case R.id.RBday: {
				emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.DAY;
			}
				break;
			case R.id.RBweek: {
				emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.WEEK;
			}
				break;
			case R.id.RBmonth: {
				emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.MON;
			}
				break;
			case R.id.RByear: {
				emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.YEAR;
			}
				break;
			default:
				break;
			}
		} else if (R.id.radiogroupshowtype == RadioGroupId) {
			switch (arg1) {
			case R.id.RBtime: {
				emCurrentTableShowType = EM_TABLE_SHOW_TYPE.TIME;
			}
				break;
			case R.id.RBdistance: {
				emCurrentTableShowType = EM_TABLE_SHOW_TYPE.DISTANCE;
			}
				break;
			case R.id.RBcalorie: {
				emCurrentTableShowType = EM_TABLE_SHOW_TYPE.CALORIE;
			}
				break;
			case R.id.RBspeed: {
				emCurrentTableShowType = EM_TABLE_SHOW_TYPE.SPEED;
			}
				break;
			default:
				break;
			}
		}
		new YDLButtonSound(this);
	}

	public void MainActivityTabChangeTitleHandle(String tabId) {
		if (tabId.equals("UserInfo")) {
			Log.e(Tag, "UserInfo Tab Change");
		} else if (tabId.equals("MoreTable")) {
			Log.e(Tag, "MoreTable Tab Change");
		} else if (tabId.equals("RunInfo")) {
			Log.e(Tag, "RunInfo Tab Change");
		} else if (tabId.equals("Setting")) {
			Log.e(Tag, "Setting Tab Change");
		} else {
			Log.e(Tag, "Quit Tab Change");
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		// show running table
		Log.e(Tag, "running table show");
		i20TablesRunningIdIndex = arg2;
		if (EM_RUNNINGIINFO_TAB_FRAME_STS.SEARCH_LISTVIEW == emRunningInfoTabFrameSts) {
			bRunningInfoTableFromDefaultListview = false;
		} else {
			bRunningInfoTableFromDefaultListview = true;
		}
		emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.TABLE;
		tab3tableSearchHandle();
		// emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.TABLE;
		// RunningInfoTabFrameInit();
		// Tab3RunningInfoFrameTitleinital();
		// MainActivitySaveFrameStsToLocal();
	}

	public boolean onBackKeyQuitHandle() {
		YDLApplication YDLApplication = (YDLApplication) getApplication();
		System.out.println("YDLApplication.getNum() ="
				+ YDLApplication.getNum());
		if (YDLApplication.getNum() <= 1) {
			// 退出APP
			AlertDialog.Builder builder = new Builder(this);
			builder.setTitle("提示");
			builder.setMessage("是否退出运动令?");
			builder.setPositiveButton("确定",
					new android.content.DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							// TODO Auto-generated method stub
							// arg0.dismiss();
							// UserLoginActivity.this.finish();
							//save runningID arraylist 
//						    editor.putInt("arrRunningIDSize", arrRunningID.size());
//						    for(int i=0;i<arrRunningID.size();i++)
//						    {
//						    	editor.remove("RunningID_" + i);  
//						    	editor.putString("RunningID_" + i, arrRunningID.get(i).toString());  
//						    }
//						    editor.commit();
							System.exit(0);
						}
					});
			builder.setNegativeButton("取消",
					new android.content.DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							// TODO Auto-generated method stub
							arg0.dismiss();
						}
					});
			builder.create().show();
			return true;
		}
		return false;

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (KeyEvent.KEYCODE_BACK == keyCode) {
			if (false == bCurrentRegisterSts) {
				return (onBackKeyQuitHandle());
			} else {
				switch (emCurrentTabNo) {
				case USERINFO: {
					return (onBackKeyQuitHandle());
				}
				case MORMTABLE: {
					if (EM_MORETABLE_TAB_FRAME_STS.TIMESELECT != emMoreTableTabFrameSts) {
						// back to time select
						emMoreTableTabFrameSts = EM_MORETABLE_TAB_FRAME_STS.TIMESELECT;
						MoreTableTabFrameInit();
						Tab2MoreTableFrameTitleinital();
						return true;
					} else {
						return (onBackKeyQuitHandle());
					}
				}
				case RUNNINGINFO: {

					if (EM_RUNNINGIINFO_TAB_FRAME_STS.DEFAULT_LISTVIEW == emRunningInfoTabFrameSts) {
						return (onBackKeyQuitHandle());
					} else if (EM_RUNNINGIINFO_TAB_FRAME_STS.TIME == emRunningInfoTabFrameSts) {
						emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.DEFAULT_LISTVIEW;
						tab3SearchThreadHandle();
						return true;
					} else if (EM_RUNNINGIINFO_TAB_FRAME_STS.SEARCH_LISTVIEW == emRunningInfoTabFrameSts) {
						emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.TIME;
						tab3SearchThreadHandle();
						return true;
					} else {
						if (true == bRunningInfoTableFromDefaultListview) {
							emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.DEFAULT_LISTVIEW;
						} else {
							emRunningInfoTabFrameSts = EM_RUNNINGIINFO_TAB_FRAME_STS.SEARCH_LISTVIEW;
						}

						tab3SearchThreadHandle();
						return true;
					}
				}
				case SETTING: {
					return (onBackKeyQuitHandle());
				}
				default:
					break;
				}
			}

		}
		return false;

	}

	/* save frame status to local XML file */
	public void MainActivitySaveFrameStsToLocal() {
		editor.putBoolean("bCurrentRegisterSts", bCurrentRegisterSts);
		editor.putInt("emCurrentTabNo", emCurrentTabNo.ordinal());
		editor.putInt("emUserInfoTabFrameSts", emUserInfoTabFrameSts.ordinal());
		editor.putInt("emMoreTableTabFrameSts",
				emMoreTableTabFrameSts.ordinal());
		editor.putInt("emRunningInfoTabFrameSts",
				emRunningInfoTabFrameSts.ordinal());
		editor.putInt("emCurrentTableArrangeTimeType",
				emCurrentTableArrangeTimeType.ordinal());
		editor.putInt("emCurrentTableShowType",
				emCurrentTableShowType.ordinal());
		editor.putString("sUserID", sUserID);
		editor.putString("sSession", sSession);
		editor.commit();

	}

	// public void BtnTouchStateSrcHandle(MotionEvent event, int srcid)
	// {
	// switch(srcid)
	// {
	// case R.id.TitleLeftButton:
	// {
	//
	// }
	// break;
	// default:break;
	// }
	//
	// if (event.getAction() == MotionEvent.ACTION_DOWN) {
	// btnClickName = btnName + "_click";
	// imgid = getResources().getIdentifier(btnClickName, "drawable",
	// "com.pro.ydl");
	// ((ImageButton) v).setImageDrawable(getResources()
	// .getDrawable(imgid));
	// } else if (event.getAction() == MotionEvent.ACTION_UP) {
	// imgid = getResources().getIdentifier(btnName, "drawable", "com.pro.ydl");
	// ((ImageButton) v).setImageDrawable(getResources()
	// .getDrawable(imgid));
	// }
	// }

	public void MainActivityAnalyzeData(ArrayList<Object> arraylist) {

		double iXValues[] = null;
		double dYValuesParamPoint[] = null;
		double dYValue[] = null;
		int iShowType = 0;
		int iTimeType = 0;
		int xlength = 0;
		double dTotleYValues = 0;

		if (true == arraylist.isEmpty() || 4 != arraylist.size()
				|| null == arraylist.get(0) || null == arraylist.get(1)) {
			return;
		}
		if (((Integer) arraylist.get(2) < 0 || (Integer) arraylist.get(2) > 3)
				|| ((Integer) arraylist.get(3) < 0 || (Integer) arraylist
						.get(3) > 3)) {
			return;
		}

		if (!(arraylist.get(0) instanceof String)) {
			return;
		}
		if (!(arraylist.get(1) instanceof double[])) {
			return;
		}

		sTableDurringTime = (String) arraylist.get(0);

		dYValuesParamPoint = (double[]) arraylist.get(1);

		xlength = dYValuesParamPoint.length;
		iXValues = new double[xlength];
		dYValue = new double[xlength];
		for (int i = 0; i < xlength; i++) {
			iXValues[i] = i + 1;
			dTotleYValues += dYValuesParamPoint[i];
			dYValue[i] = dYValuesParamPoint[i];
		}

		iShowType = (Integer) arraylist.get(2);
		emCurrentTableShowType = EM_TABLE_SHOW_TYPE.values()[iShowType];

		iTimeType = (Integer) arraylist.get(3);
		emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.values()[iTimeType];
	}

	public void MainActivityAnalyzeFavorateHashDate() {

	}

	public void MainActivityAnalyzeHashData(Hashtable<String, Object> param) {
		double[] temp = null;
		Date tempDate = null;
		if (null == param || 6 != param.size()) {
			sCurrentTableTimedurring = null;
			sStartTime = null;
			sStopTime = null;
			dCurrentTableXDataArray = null;
			dCurrentTableYDataArray = null;
			emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.DAY;
			emCurrentTableShowType = EM_TABLE_SHOW_TYPE.TIME;
			return;
		}

		if (null != param.get("iTimeType")) {
			emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.values()[(Integer) param
					.get("iTimeType")];
		} else {
			emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.DAY;
		}
		if (null != param.get("iShowType")) {
			emCurrentTableShowType = EM_TABLE_SHOW_TYPE.values()[(Integer) param
					.get("iShowType")];
		} else {
			emCurrentTableShowType = EM_TABLE_SHOW_TYPE.TIME;
		}

		if (null != param.get("timeBucket")) {
			sCurrentTableTimedurring = (String) param.get("timeBucket");
		}
		if (null != param.get("startTime")) {
			tempDate = (Date) param.get("startTime");
			dataStartTime = (Date) param.get("startTime");
			sStartTime = tempDate.toString();
		}
		if (null != param.get("endTime")) {
			tempDate = (Date) param.get("endTime");
			dataEndTime = (Date) param.get("endTime");
			sStopTime = tempDate.toString();
		}
		if (null != param.get("yArray")) {
			try {
				temp = (double[]) param.get("yArray");
				int aa = temp.length;
				dCurrentTableYDataArray = new double[(temp.length)];
				dCurrentTableXDataArray = new double[(temp.length)];
			} catch (Exception e) {
				e.printStackTrace();
			}
			for (int i = 0; i < (temp.length); i++) {
				if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.TIME) {
					dCurrentTableYDataArray[i] = temp[i] / 60;
				} else {
					dCurrentTableYDataArray[i] = temp[i];
				}
			}

			for (int i = 0; i < temp.length; i++) {
				dCurrentTableXDataArray[i] = i + 1;
			}
		}

	}

	public class MyPagerAdapter extends PagerAdapter {

		@Override
		public void destroyItem(View v, int position, Object arg2) {
			// TODO Auto-generated method stub
			((ViewPager) v).removeView((View) arg2);
			// mListViews.remove(position);
		}

		@Override
		public void finishUpdate(View arg0) {
			// TODO Auto-generated method stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return tableviews.size();

		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			// TODO Auto-generated method stub
			((ViewPager) arg0).addView(tableviews.get(arg1));
			return tableviews.get(arg1);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			// TODO Auto-generated method stub
			return arg0 == (arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
			// TODO Auto-generated method stub

		}

		@Override
		public Parcelable saveState() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public int getItemPosition(Object object) {
			// TODO Auto-generated method stub
			for (int i = 0; i < tableviews.size(); i++) {
				if (object.equals(tableviews.get(i))) {
					return i;
				}
			}
			return POSITION_NONE;
		}

	};

	public void MainActivityStartService() {
		Intent intent = new Intent();
		intent.setClass(MainHomeActivity.this, MainService.class);
		this.startService(intent);
	}

	public void MainActivityEndService() {
		Intent intent = new Intent();
		intent.setClass(MainHomeActivity.this, MainService.class);
		this.stopService(intent);
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub
	}

	@Override
	// TODO Auto-generated method stub
	public void onPageSelected(int arg0) {
		iViewPagerCurrentPage = arg0;
		Hashtable<String, String> htTotleData = null;
		if(arrRunningID.size() > 0)
		{
			sRunningID = arrRunningID.get(arg0).toString();
		}
		else
		{
			sRunningID = "";
		}
		Hashtable<String, Object> map = null;
		try {
			map = database.getOneReportById(
					iStoreTableIdArray[iViewPagerCurrentPage], this);
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(map != null)
		{
			map.remove("ID");
		}
		MainActivityAnalyzeHashData(map);
		Tab1TableFrameTitleSet(true);
		MainActivityTitleFrameInitial();
		
		textviewUserInfoTotleSum.setVisibility(View.GONE);
		if(sRunningID != "" && sRunningID.length() > 0)
		{
			Control con = new Control();
			htTotleData = con.get20tableElementInfo(this, Integer.parseInt(sUserID), Integer.parseInt(sRunningID));
			textviewUserInfoTotleSum.setText("运动距离:"+htTotleData.get("Distance")
					+"公里"+";运动时间："+htTotleData.get("SportTime")+"分钟");
			textviewUserInfoTotleSum.setVisibility(View.VISIBLE);
		}
		else if(emCurrentTableArrangeTimeType == EM_TABLE_ARRANGETIME_TYPE.DAY)
		{
			Timestamp tsStart = new Timestamp(dataStartTime.getTime() );
			String totleinfo = database.getDaySummaryComments(sUserID, 
							0, "1", tsStart.toString(), emCurrentTableShowType.ordinal(), MainHomeActivity.this);		
			textviewUserInfoTotleSum.setText(totleinfo);
			textviewUserInfoTotleSum.setVisibility(View.VISIBLE);
		}
		else
		{
			textviewUserInfoTotleSum.setText("");
		}
	}

	public void MoreTableWheelTimeInit() {
		final Integer days[][] = new Integer[][] {
				new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
						15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
						29, 30, 31 },
				new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
						15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28 },
				new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
						15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
						29, 30 },
				new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
						15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
						29 } };

		final WheelView year = (WheelView) findViewById(R.id.moretabledatePicker_year);
		final WheelView months = (WheelView) findViewById(R.id.moretabledatePicker_month);
		final WheelView day = (WheelView) findViewById(R.id.moretabledatePicker_day);

		// Initial year wheel
		year.setAdapter(new NumericWheelAdapter(1900, 2300));
		year.setLabel("年");
		year.setCyclic(true);
		year.setVisibleItems(5);
		// Initial month wheel
		months.setAdapter(new NumericWheelAdapter(1, 12));
		months.setLabel("月");
		months.setCyclic(true);
		months.setVisibleItems(5);
		// Initial day wheel
		day.setVisibleItems(5);
		day.setAdapter(new ArrayWheelAdapter<Integer>(days[0]));
		day.setCyclic(true);
		day.setLabel("日");

		// set current time
		// iDayUserSelect [0,Max]
		// iMonthsUserSelect [0,11]
		// iYearUserSelect [0,year -1990]

		Calendar c = Calendar.getInstance();
		iDayUserSelect = c.get(Calendar.DAY_OF_MONTH);
		iMonthsUserSelect = c.get(Calendar.MONTH);
		iYearUserSelect = c.get(Calendar.YEAR);
		day.setCurrentItem(iDayUserSelect - 1);
		months.setCurrentItem(iMonthsUserSelect);
		year.setCurrentItem(iYearUserSelect - 1900);
		iDayUserSelect = iDayUserSelect - 1;
		iYearUserSelect = iYearUserSelect - 1900;

		OnWheelChangedListener WheelViewListener = new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				iYearUserSelect = year.getCurrentItem();
				iMonthsUserSelect = months.getCurrentItem();
				iDayUserSelect = day.getCurrentItem();
				if (day == wheel) {
					return;
				}
				boolean isLeapYear = false;
				if (iYearUserSelect % 400 == 0 || (iYearUserSelect % 100 != 0)
						&& (iYearUserSelect % 4 == 0)) {
					isLeapYear = true;
				} else {
					isLeapYear = false;
				}
				switch (iMonthsUserSelect) {
				case 0:
				case 2:
				case 4:
				case 6:
				case 7:
				case 9:
				case 11:
					day.setAdapter(new ArrayWheelAdapter<Integer>(days[0]));
					break;
				case 1:
					if (isLeapYear) {
						day.setAdapter(new ArrayWheelAdapter<Integer>(days[3]));
					} else {
						day.setAdapter(new ArrayWheelAdapter<Integer>(days[1]));
					}
					break;
				case 3:
				case 5:
				case 8:
				case 10:
					day.setAdapter(new ArrayWheelAdapter<Integer>(days[2]));
					break;
				default:
					break;
				}
				day.setCurrentItem(0);
				iDayUserSelect = 0;
			}
		};
		// add listeners
		day.addChangingListener(WheelViewListener);
		months.addChangingListener(WheelViewListener);
		year.addChangingListener(WheelViewListener);
	}

	public void RunningInfoWheelTimeInit() {

		final Integer days[][] = new Integer[][] {
				new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
						15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
						29, 30, 31 },
				new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
						15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28 },
				new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
						15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
						29, 30 },
				new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
						15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
						29 } };

		final WheelView year = (WheelView) findViewById(R.id.runninginfodatePicker_year);
		final WheelView months = (WheelView) findViewById(R.id.runninginfodatePicker_month);
		final WheelView day = (WheelView) findViewById(R.id.runninginfodatePicker_day);

		// Initial year wheel
		year.setAdapter(new NumericWheelAdapter(1900, 2300));
		year.setLabel("年");
		year.setCyclic(true);

		// Initial month wheel
		months.setAdapter(new NumericWheelAdapter(1, 12));
		months.setLabel("月");
		months.setCyclic(true);

		// Initial day wheel
		day.setVisibleItems(5);
		day.setAdapter(new ArrayWheelAdapter<Integer>(days[0]));
		day.setCyclic(true);
		day.setLabel("日");

		// set current time
		Calendar c = Calendar.getInstance();
		iDayRunTableUserSelect = c.get(Calendar.DAY_OF_MONTH);
		iMonthsRunTableUserSelect = c.get(Calendar.MONTH);
		iYearRunTableUserSelect = c.get(Calendar.YEAR);
		day.setCurrentItem(iDayRunTableUserSelect - 1);
		months.setCurrentItem(iMonthsRunTableUserSelect);
		year.setCurrentItem(iYearRunTableUserSelect - 1900);
		iDayRunTableUserSelect = iDayRunTableUserSelect - 1;
		iYearRunTableUserSelect = iYearRunTableUserSelect - 1900;

		OnWheelChangedListener WheelViewListener = new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				iYearRunTableUserSelect = year.getCurrentItem();
				iMonthsRunTableUserSelect = months.getCurrentItem();
				iDayRunTableUserSelect = day.getCurrentItem();
				if (day == wheel) {
					return;
				}
				boolean isLeapYear = false;
				if (iYearRunTableUserSelect % 400 == 0
						|| (iYearRunTableUserSelect % 100 != 0)
						&& (iYearRunTableUserSelect % 4 == 0)) {
					isLeapYear = true;
				} else {
					isLeapYear = false;
				}
				switch (iMonthsRunTableUserSelect) {
				case 0:
				case 2:
				case 4:
				case 6:
				case 7:
				case 9:
				case 11:
					day.setAdapter(new ArrayWheelAdapter<Integer>(days[0]));
					break;
				case 1:
					if (isLeapYear) {
						day.setAdapter(new ArrayWheelAdapter<Integer>(days[3]));
					} else {
						day.setAdapter(new ArrayWheelAdapter<Integer>(days[1]));
					}
					break;
				case 3:
				case 5:
				case 8:
				case 10:
					day.setAdapter(new ArrayWheelAdapter<Integer>(days[2]));
					break;
				default:
					break;
				}
				day.setCurrentItem(0);
			}
		};
		// add listeners
		day.addChangingListener(WheelViewListener);
		months.addChangingListener(WheelViewListener);
		year.addChangingListener(WheelViewListener);

	}

	public void SettingTabSubmitInfoHandle() {
		String sSex = null;
		String sEmail = (ETSettingEmail.getText()).toString();
		String sOldPasswd = (ETSettingOldPasswd.getText()).toString();
		String sNewPasswd = (ETSettingNewPasswd.getText()).toString();
		String sNewPasswdConfirm = (ETSettingNewPasswdConfirm.getText()).toString();
		String sHeight = (ETSettingHeight.getText()).toString();
		String sWeight = (ETSettingWeight.getText()).toString();
		String strUserOldPassword = sharedPreferences.getString(
				"sUserPassword", "");

		if (R.id.configBoy == RGSettingSex.getCheckedRadioButtonId()) {
			sSex = "F";
		} else {
			sSex = "M";
		}

		// check email
		Pattern pattern = Pattern
				.compile("^([a-z0-9a-z]+[-|\\.]?)+[a-z0-9a-z]@([a-z0-9a-z]+(-[a-z0-9a-z]+)?\\.)+[a-za-z]{2,}$");
		Matcher matcher = pattern.matcher(sEmail);
		if (!matcher.matches() && !sEmail.equals("admin")) {
			ShowToast(getApplicationContext(), "您输入的邮箱格式有误，请重新尝试");
			return;
		}
		if (!strUserOldPassword.equals(sOldPasswd)) {
			ShowToast(getApplicationContext(), "您输入的原密码有误");
			return;
		}
		if(!sNewPasswd.equals(sNewPasswdConfirm))
		{
			ShowToast(getApplicationContext(), "新密码和确认密码必须一致");
			return;
		}
		// all the user input is right
		strUserYear = spinnerYear.getSelectedItem().toString();
		strUserMonth = spinnerMonth.getSelectedItem().toString();
		strUserDay = spinnerDay.getSelectedItem().toString();
		strUserbirthday = strUserYear + "-" + strUserMonth.replace("月", "")
				+ "-" + strUserDay.replace("日", "");

		SettingTabThreadSubmit(sEmail, sOldPasswd,sNewPasswd, strUserbirthday, sHeight,
				sWeight, sSex);
		progdialogSettingSubmitUserInfo = ProgressDialog.show(
				MainHomeActivity.this, "正在加载", "系统正在提交用户数据");
	}

	public void LineTableClickListener(final GraphicalView chartView) {
		chartView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				SeriesSelection seriesSelection = chartView
						.getCurrentSeriesAndPoint();

				double[] xy = chartView.toRealPoint(0);
				// long[] xValue = new long[2880];
				String xMessage = "";
				// for(int i =0; i < xValue.length; i++)
				// {
				// xValue[i] = i*30;
				// }

				if (seriesSelection == null) {
				} else {
					int pointIndex = seriesSelection.getPointIndex();
					// if(pointIndex < 2880)
					// {
					// xMessage = getCurrentTime(xValue[pointIndex]);
					// }
					if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.TIME) {
						ShowToast(MainHomeActivity.this, "您运动了"
								+ (float) seriesSelection.getValue() + "分钟");
					} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.DISTANCE) {
						ShowToast(MainHomeActivity.this, "您运动的距离是"
								+ (float) seriesSelection.getValue() + "千米");
					} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.CALORIE) {
						ShowToast(MainHomeActivity.this, "您消耗了"
								+ (float) seriesSelection.getValue() + "卡路里");
					} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.SPEED) {
						ShowToast(MainHomeActivity.this, "您运动的速度是"
								+ (float) seriesSelection.getValue() + "千米/小时");
					} else {
						ShowToast(MainHomeActivity.this, "您所查看的值是"
								+ (float) seriesSelection.getValue());
					}
				}

			}
		});
	}

	public void RunningLineTableClickListener(final GraphicalView chartView) {
		chartView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				SeriesSelection seriesSelection = chartView
						.getCurrentSeriesAndPoint();
				// String[] temp = startTime.split(" ");
				// String xMessage = "";
				if (seriesSelection == null) {
				}
				// else if(temp.length > 5)
				// {
				// String[] time = temp[3].split(":");
				// int hour = Integer.parseInt(time[0]);
				// int minute = Integer.parseInt(time[1]);
				// int second = Integer.parseInt(time[2]);
				// int pointIndex = seriesSelection.getPointIndex();
				// long tolalSecond = hour*3600 + minute*60 + second +
				// pointIndex*30;
				// xMessage = getCurrentTime(tolalSecond);
				// ShowToast(MainHomeActivity.this,"您运动的速度是" + (float)
				// seriesSelection.getValue() +"千米/小时");
				// }
				else {
					double[] xy = chartView.toRealPoint(0);
					ShowToast(MainHomeActivity.this, "您运动的速度是"
							+ (float) seriesSelection.getValue() + "千米/小时");
				}
			}
		});
	}

	public void BarTableClickListener(final GraphicalView chartView) {
		chartView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				SeriesSelection seriesSelection = chartView
						.getCurrentSeriesAndPoint();
				double[] xy = chartView.toRealPoint(0);
				if (seriesSelection == null) {
				} else {
					if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.TIME) {
						ShowToast(MainHomeActivity.this, "您运动了"
								+ (float) seriesSelection.getValue() + "分钟");
					} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.DISTANCE) {
						ShowToast(MainHomeActivity.this, "您运动的距离是"
								+ (float) seriesSelection.getValue() + "千米");
					} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.CALORIE) {
						ShowToast(MainHomeActivity.this, "您消耗了"
								+ (float) seriesSelection.getValue() + "卡路里");
					} else if (emCurrentTableShowType == EM_TABLE_SHOW_TYPE.SPEED) {
						ShowToast(MainHomeActivity.this, "您运动的速度是"
								+ (float) seriesSelection.getValue() + "千米/小时");
					} else {
						ShowToast(MainHomeActivity.this, "您所查看的值是"
								+ (float) seriesSelection.getValue());
					}
				}

			}
		});
	}

	public boolean checkDataBase() {
		String DB_PATH, DB_NAME;
		DB_PATH = "/data/data/com.pro.ydl/databases";
		DB_NAME = "yundongling.db";
		File file = new File(DB_PATH, DB_NAME);
		return file.exists();
	}

	public static void copyDatabaseFile(Context context, boolean isfored) {
		String DATABASES_DIR, DATABASE_NAME;
		DATABASES_DIR = "/data/data/com.pro.ydl/databases";
		DATABASE_NAME = "yundongling.db";
		File dir = new File(DATABASES_DIR);
		if (!dir.exists() || isfored) {
			try {
				dir.mkdir();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		File dest = new File(dir, DATABASE_NAME);
		if (dest.exists() && !isfored) {
			return;
		}

		try {
			if (dest.exists()) {
				dest.delete();
			}
			dest.createNewFile();
			InputStream in = context.getResources().openRawResource(
					R.raw.yundongling);
			int size = in.available();
			byte buf[] = new byte[size];
			in.read(buf);
			in.close();
			FileOutputStream out = new FileOutputStream(dest);
			out.write(buf);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void CheckCurrentRadioShowType() {
		int iTempSelectDataType = moretabletabdateradiogroup
				.getCheckedRadioButtonId();
		int iTempSelectShowType = moretabletabshowtyperadiogroup
				.getCheckedRadioButtonId();

		switch (iTempSelectDataType) {
		case R.id.RBday:
			emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.DAY;
			break;
		case R.id.RBweek:
			emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.WEEK;
			break;
		case R.id.RBmonth:
			emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.MON;
			break;
		case R.id.RByear:
			emCurrentTableArrangeTimeType = EM_TABLE_ARRANGETIME_TYPE.YEAR;
			break;
		default:
			break;
		}
		switch (iTempSelectShowType) {
		case R.id.RBtime:
			emCurrentTableShowType = EM_TABLE_SHOW_TYPE.TIME;
			break;
		case R.id.RBdistance:
			emCurrentTableShowType = EM_TABLE_SHOW_TYPE.DISTANCE;
			break;
		case R.id.RBcalorie:
			emCurrentTableShowType = EM_TABLE_SHOW_TYPE.CALORIE;
			break;
		case R.id.RBspeed:
			emCurrentTableShowType = EM_TABLE_SHOW_TYPE.SPEED;
			break;
		default:
			break;
		}
	}

	public void ShowToast(Context context, String strShowMessage) {
		Toast toast = Toast.makeText(context, strShowMessage,
				Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}

	public void SettingTabThreadDataReq(final String email,
			final String password) {
		new Thread() {
			@Override
			public void run() {
				Message msg = new Message();
				msg.what = MESSAGE_SETTING_GET_USE_INFO;
				getUserInfo = database
						.getUserInfo(email, MainHomeActivity.this);
				if (null == getUserInfo) {
					msg.arg1 = 0;
				} else {
					msg.arg1 = 1;
				}
				handle.sendMessage(msg);
			}
		}.start();

	}

	public void SettingTabThreadSubmit(final String sEmail,final String sPasswd,
			final String sNewPasswd, final String strUserbirthday2,
			final String sHeight, final String sWeight, final String sSex) {
		new Thread() {
			@Override
			public void run() {
				boolean bRet = false;
				Message msg = new Message();
				msg.what = MESSAGE_SETTING_SUBMIT_USER_INFO;
				bRet = database.updateUserInfo(sEmail,sPasswd, sNewPasswd,
						strUserbirthday2, sHeight, sWeight, sSex, "", "", "",
						"",MainHomeActivity.this);
				if (false == bRet) {
					msg.arg1 = 0;
				} else {
					msg.arg1 = 1;
				}
				handle.sendMessage(msg);
			}
		}.start();
	}

	public void MainActivityDownDataFormWeb() {
		if (false == bCurrentRegisterSts) {
			return;
		}
		progdialogMainDownLoadToBD = ProgressDialog.show(MainHomeActivity.this,
				"正在加载", "系统正在下载更新数据");
		new Thread() {
			@Override
			public void run() {
				boolean bWhetherDown = false;
				Message msg = new Message();
				msg.what = MESSAGE_MAIN_DOWNLOAD_DATA_TO_BD;
				long lDownDataSum = 0;
				for (int i = 0; i < 4; i++) {
					bWhetherDown = database
							.whetherDownload(MainHomeActivity.this, i,
									Integer.parseInt(sUserID));
					if (true == bWhetherDown) {
						try {

							lDownDataSum = database.downloadDataToDB(sSession,
									new Date(0), new Date(0), "1", i,
									MainHomeActivity.this);
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							lDownDataSum = -1;
						}
					}

				}
				if (false == bWhetherDown) {
					msg.arg1 = -1;
				} else {
					if (-1 == lDownDataSum) {
						msg.arg1 = 0;
					} else if (0 == lDownDataSum) {
						msg.arg1 = -1;
					} else {
						msg.arg1 = 1;
					}
				}

				handle.sendMessage(msg);
			}
		}.start();

	}

	public void Tab1TableFrameTitleSet(boolean show) {
		if (false == show) {
			textviewUserInfoTimeDurring.setVisibility(View.GONE);
			textviewUserInfoTotleSum.setVisibility(View.GONE);
		} else {
			textviewUserInfoTimeDurring.setText(sCurrentTableTimedurring);
			textviewUserInfoTimeDurring.setVisibility(View.VISIBLE);
			textviewUserInfoTotleSum.setVisibility(View.VISIBLE);
		}
	}

	public void Tab2TableFrameTitleSet(boolean show) {

		if (false == show) {
			moretabletabtimedurringtextview.setVisibility(View.GONE);
			moretabletabtotolesumtextview.setVisibility(View.GONE);
		} else {
			moretabletabtimedurringtextview.setText(sCurrentTableTimedurring);
			moretabletabtimedurringtextview.setVisibility(View.VISIBLE);
			if(emCurrentTableArrangeTimeType != EM_TABLE_ARRANGETIME_TYPE.DAY)
			{
				moretabletabtotolesumtextview.setText("");
			}
			else
			{

				moretabletabtotolesumtextview.setText(sMoreTableSummary);
			
			}
			moretabletabtotolesumtextview.setVisibility(View.VISIBLE);
		}
	}

	public void Tab2SearchThreadHandle() {
		progdialogTab2Search = ProgressDialog.show(MainHomeActivity.this,
				"正在加载", "系统正在获取用户数据");
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				String strUserEmail = sharedPreferences.getString("sUserName",
						"");
				String strUserPassword = sharedPreferences.getString(
						"sUserPassword", "");
				String strSessionID = database.login(strUserEmail,
						strUserPassword, "1");
				sSessionID = strSessionID;
				Date date = new Date(iYearUserSelect, iMonthsUserSelect,
						iDayUserSelect + 1);
				long lResult = 0;
				Message msg = new Message();
				msg.what = MESSAGE_TAB2_SEARCH_RESULT;
				// web以及数据库的判断下载
				// 第二个参数有问题，查询的时候，保存的session早就过期了
				try {
					if (isOnline()) {
						//if (true) {
						lResult = database.deleteAndDownloadData(sUserID,
								strSessionID, date, "1",
								emCurrentTableShowType.ordinal(),
								emCurrentTableArrangeTimeType.ordinal(),
								MainHomeActivity.this);
					} else {
						lResult = 1;
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					lResult = 0;
				}
				if (0 == lResult) {
					msg.arg1 = 0;
				}
				else if(2 == lResult)
				{
					msg.arg1 = 0;
					strDownLoadErrorMessage  = "您查询的数据不存在";
				}
				else {
					msg.arg1 = 1;
					Timestamp tsDate = new Timestamp(date.getTime());
					if(EM_TABLE_ARRANGETIME_TYPE.DAY == emCurrentTableArrangeTimeType)
						sMoreTableSummary = database.getDaySummaryComments(sUserID, 
							0, "1", tsDate.toString(), emCurrentTableShowType.ordinal(), MainHomeActivity.this);
				}
				handle.sendMessage(msg);
			}

		}).start();
	}

	public void tab3SearchThreadHandle() {
		if (EM_CURRENT_TAB_NO.RUNNINGINFO != emCurrentTabNo) {
			return;
		}
		if (true == bFirstShowTab3) {
			bFirstShowTab3 = false;
			runninginfotabdatepicker.setVisibility(View.GONE);
			tab3listview.setVisibility(View.GONE);
			tab3tablerelativelayout.setVisibility(View.GONE);
		}
		if (EM_RUNNINGIINFO_TAB_FRAME_STS.TIME == emRunningInfoTabFrameSts) {
			// 不处理
			runninginfotabdatepicker.setVisibility(View.VISIBLE);
			tab3listview.setVisibility(View.GONE);
			tab3tablerelativelayout.setVisibility(View.GONE);
			Tab3RunningInfoFrameTitleinital();
		} else if (EM_RUNNINGIINFO_TAB_FRAME_STS.DEFAULT_LISTVIEW == emRunningInfoTabFrameSts) {
			tab3DefaultListSearchHandle();
		} else if (EM_RUNNINGIINFO_TAB_FRAME_STS.SEARCH_LISTVIEW == emRunningInfoTabFrameSts) {
			tab3ListSearchHandle();
		} else {
			// 跑步table
			tab3tableSearchHandle();
		}
	}

	public void tab3DefaultListSearchHandle() {
		progdialogTab3Search = ProgressDialog.show(MainHomeActivity.this,
				"正在加载", "系统正在获取用户数据");
		// 下载设置时间的listview
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				long lResult = 0;
				String strUserEmail = sharedPreferences.getString("sUserName",
						"");
				String strUserPassword = sharedPreferences.getString(
						"sUserPassword", "");
				String strSessionID = database.login(strUserEmail,
						strUserPassword, "1");
				sSessionID = strSessionID;
				Message msg = new Message();
				msg.what = MESSAGE_TAB3_DEFAULTLISTSEARCH_RESULT;
				Date current = new Date(System.currentTimeMillis());
				// 第一个参数有问题
				if (isOnline()) {
					lResult = database.deleteAndDownload20PerRunning(
							strSessionID, current, MainHomeActivity.this,
							sUserID, "1");
				} else {
					lResult = 1;
				}
				if (0 == lResult) {
					msg.arg1 = 0;
				} else {
					msg.arg1 = 1;
				}
				handle.sendMessage(msg);
			}

		}).start();
	}

	public void tab3ListSearchHandle() {
		progdialogTab3Search = ProgressDialog.show(MainHomeActivity.this,
				"正在加载", "系统正在获取用户数据");
		// 下载设置时间的listview
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				long lResult = 0;
				String strUserEmail = sharedPreferences.getString("sUserName",
						"");
				String strUserPassword = sharedPreferences.getString(
						"sUserPassword", "");
				String strSessionID = database.login(strUserEmail,
						strUserPassword, "1");
				sSessionID = strSessionID;
				Message msg = new Message();
				msg.what = MESSAGE_TAB3_USERLISTSEARCH_RESULT;
				Date date = new Date(iYearRunTableUserSelect,
						iMonthsRunTableUserSelect, iDayRunTableUserSelect + 1);
				// 第一个参数有问题
				if (isOnline()) {
					lResult = database.deleteAndDownload20PerRunning(
							strSessionID, date, MainHomeActivity.this, sUserID,
							"1");
				} else {
					lResult = 1;
				}
				if (0 == lResult) {
					msg.arg1 = 0;
				} else {
					msg.arg1 = 1;
				}
				handle.sendMessage(msg);
			}

		}).start();
	}

	public void tab3tableSearchHandle() {
		progdialogTab3Search = ProgressDialog.show(MainHomeActivity.this,
				"正在加载", "系统正在获取用户数据");
		// 下载设置时间的listview
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// table删除调用
				long lResult = 0;
				Message msg = new Message();
				String strUserEmail = sharedPreferences.getString("sUserName",
						"");
				String strUserPassword = sharedPreferences.getString(
						"sUserPassword", "");
				String strSessionID = database.login(strUserEmail,
						strUserPassword, "1");
				sSessionID = strSessionID;
				msg.what = MESSAGE_TAB3_TABLESEARCH_RESULT;
				if (null == i20TablesRunningId) {
					Cursor cursorListView = null;
					cursorListView = database.get20table(MainHomeActivity.this,
							Integer.parseInt(sUserID));
					int iCursorItem = cursorListView.getCount();
					i20TablesRunningId = new int[iCursorItem];
					for (int i = 0; i < iCursorItem; i++) {
						int index = cursorListView.getColumnIndex("RunningID");
						cursorListView.moveToNext();
						i20TablesRunningId[i] = cursorListView.getInt(index);

					}
				}
				if(isOnline())
				{
				lResult = database.deleteAndDownload20Elment(
						MainHomeActivity.this, strSessionID,
						Integer.parseInt(sUserID),
						i20TablesRunningId[i20TablesRunningIdIndex], "1");
				}
				else
				{
					lResult = 1;
				}
				if (0 == lResult) {
					msg.arg1 = 0;
				} else {
					msg.arg1 = 1;
				}
				handle.sendMessage(msg);
			}

		}).start();

	}

	public void logoutApp(View view) {
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("提示");
		builder.setMessage("是否要注销当前用户？");
		builder.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						SharedPreferences sharedPreferences = MainHomeActivity.this
								.getSharedPreferences("YDL",
										Context.MODE_PRIVATE);
						Editor editor = sharedPreferences.edit();
						editor.putString("sUserName", "");
						editor.putString("sUserPassword", "");
						editor.commit();
						bCurrentRegisterSts = false;
						Intent intent = new Intent();
						intent.setClass(MainHomeActivity.this,
								UserLoginActivity.class);
						MainHomeActivity.this.startActivity(intent);
						MainHomeActivity.this.finish();
						mTabHost.setCurrentTab(0);
						emCurrentTabNo = EM_CURRENT_TAB_NO.values()[0];
						iPreTabNo = 0;
						MainActivitySaveFrameStsToLocal();
					}
				});
		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						arg0.dismiss();
					}
				});
		builder.create().show();
	}

	public String getCurrentTime(long second) {
		String strTime = "";
		long intHour = second / 3600;
		long intMinute = second % 3600 / 60;
		long intSecond = second % 60;
		strTime = "在" + intHour + "时" + intMinute + "分" + intSecond + "秒, ";
		return strTime;
	}

	private Boolean isOnline() {
		try
		{
			ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo ni = cm.getActiveNetworkInfo();
			if (ni != null && ni.isConnected()) {
				return true;
			}
			return false;
		}
		catch(Exception e)
		{
			return false;
		}
	}
	
	private void StartFrameHandle()
	{
		RelativeLayout layoutTab1 = (RelativeLayout)findViewById(R.id.tab1);
		final int ImageIDs[]={
				R.drawable.startup_screen01,
				R.drawable.startup_screen02,
				R.drawable.startup_screen03,
				R.drawable.startup_screen04,
				R.drawable.startup_screen05
			};

		if(true == database.haveDataOrNot(this))
		{
			if(null != mStartFrameViewPager)
			{
				layoutTab1.removeView(mStartFrameViewPager);
			}
			userinfoviewpager.setVisibility(View.VISIBLE);
			imagebuttonUserInfoDeleteTable.setVisibility(View.VISIBLE);
			textviewUserInfoTimeDurring.setVisibility(View.VISIBLE);
			textviewUserInfoTotleSum.setVisibility(View.VISIBLE);
			findViewById(R.id.tab1LeftArrow).setVisibility(View.VISIBLE);
			findViewById(R.id.tab1RightArrow).setVisibility(View.VISIBLE);
			return;
		}
		lvStartFrameViews = new ArrayList<View>();
		for(int i = 0; i<ImageIDs.length; i++)
		{
			ImageView mImageView = new ImageView(MainHomeActivity.this);
			mImageView.setImageResource(ImageIDs[i]);
			lvStartFrameViews.add(mImageView);
		}
		try
		{
		mStartFrameViewPager.setAdapter(new PagerAdapter(){
			@Override
			public int getCount() {
				// TODO Auto-generated method stub

				return (lvStartFrameViews.size());
			}

			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				// TODO Auto-generated method stub
				return (arg0 == arg1);
			}
			
			@Override
			public Object instantiateItem(View arg0, int arg1) {
				// TODO Auto-generated method stub
				((ViewPager) arg0).addView(lvStartFrameViews.get(arg1));
				return lvStartFrameViews.get(arg1);
			}
			@Override
			public void destroyItem(View v, int position, Object arg2) {
				// TODO Auto-generated method stub
				((ViewPager) v).removeView((View) arg2);
			}

			@Override
			public void finishUpdate(View arg0) {
				// TODO Auto-generated method stub
			}

			@Override
			public void restoreState(Parcelable arg0, ClassLoader arg1) {
				// TODO Auto-generated method stub

			}

			@Override
			public Parcelable saveState() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public void startUpdate(View arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public int getItemPosition(Object object) {
				// TODO Auto-generated method stub
				for (int i = 0; i < lvStartFrameViews.size(); i++) {
					if (object.equals(lvStartFrameViews.get(i))) {
						return i;
					}
				}
				return POSITION_NONE;
			}
		});
		}
		catch(Exception e)
		{
			e.printStackTrace();		
		}
		layoutTab1.addView(mStartFrameViewPager);
		userinfoviewpager.setVisibility(View.GONE);
		imagebuttonUserInfoDeleteTable.setVisibility(View.GONE);
		textviewUserInfoTimeDurring.setVisibility(View.GONE);
		textviewUserInfoTotleSum.setVisibility(View.GONE);
		findViewById(R.id.tab1LeftArrow).setVisibility(View.GONE);
		findViewById(R.id.tab1RightArrow).setVisibility(View.GONE);
	}
	private String GetLoginName()
	{
		String sName = null;
		boolean bResgister = false;
		sName = sharedPreferences.getString("sUserName", "0");
		bResgister = sharedPreferences.getBoolean("bCurrentRegisterSts", false);
		if(false == bResgister)
		{
			sName = "(未登入)";
			return (sName);
		}
		if(sName.equals("0"))
		{
			sName =null;
		}
		else
		{
			if(sName.length() > 5)
			{
				sName = "("+sName.substring(0,5)+")";
				sName += "...";
			}
			else
			{
				sName = "("+sName+")";
			}
		}
		return (sName);
		
	}
}
